[英]Why do I have an error for adding a variable to an ArrayList?
我有一個像這樣的課:
public class Author
{
public ArrayList<String> quotes;
private String name;
public Author(String name)
{
this.name = name;
}
}
現在,我想在另一個類中將內容添加到稱為引號的數組列表中:
public class Page
{
Author John = new Author("John Smith");
John.quotes.add("asdf"); //but this is wrong. The add() isn't recognized
...
}
如您所見,我無法將變量添加到另一個類的ArrayList引號中。 我怎樣才能做到這一點?
因為您沒有實例化quotes
。 你可以做類似的事情
public Author(String name)
{
this.name = name;
this.quotes = new ArrayList<>();
}
您沒有創建public ArrayList<String> quotes;
的對象public ArrayList<String> quotes;
它將在以下情況下引用null
作者John =新作者(“ John Smith”); //運行此代碼時。
引號實際上是指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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.