簡體   English   中英

為什么在將變量添加到ArrayList時出錯?

[英]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

如果尚未實例化 ArrayList<String>則必須獲取NullPointerException

但是,如果像下面的圖片那樣實例化它,那肯定會成功。

參考此輸出,

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM