为什么在向ArrayList添加变量时出错?

时间:2016-02-22 05:52:14

标签: java arraylist

我有一个如下课程:

public class Author
{

   public ArrayList<String> quotes;
   private String name;

   public Author(String name)
   {
      this.name = name;

   }
}

现在我想在另一个类中添加名为引号的arraylist:

public class Page 
{

    Author John = new Author("John Smith");

    John.quotes.add("asdf"); //but this is wrong. The add() isn't recognized

    ...
}

如您所见,我无法将变量添加到另一个类的ArrayList引号中。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

因为您没有实例化quotes。你可以做点什么

public Author(String name)
{
    this.name = name;
    this.quotes = new ArrayList<>();
}

答案 1 :(得分:0)

您没有创建public ArrayList<String> quotes;的对象

时会引用null
  

作者约翰=新作者(“约翰史密斯”); //运行此代码时。

引号实际上会引用null。这就是Exception被提升背后的原因。

希望你的立场。

public class Author
{

   public ArrayList<String> quotes;
   private String name;
   public Author(){
     this.quotes = new ArrayList<String>();
    }
   public Author(String name)
   {
      this();
      this.name = name;

   }
}

尝试Class Author的此定义。解决您的exception

答案 2 :(得分:0)

如果您未实例化 ArrayList<String>,那么您必须获得NullPointerException

但如果您将其实例化如下图所示,您一定会获得成功。

参考此输出,

enter image description here