亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試從其他類訪問 ArrayList 時出現 NullPointerException

嘗試從其他類訪問 ArrayList 時出現 NullPointerException

飲歌長嘯 2023-08-16 10:49:59
我正在編寫一個管理庫存的程序,例如通過添加、刪除和租用物品,所有這些都是通過在面向對象的氛圍中使用多個類來實現的。下面是我的實現類(Driver)。Driver.javapublic class Driver {   public static void main(String[] args)   {      ABCRentals abc = new ABCRentals();      Furniture item1 = new Furniture();      boolean flag = abc.add(item1);      List<Integer> idList = abc.getIDList();      String[] itemTypes = abc.getItemArray();      System.out.println("Item ID Numbers: " + Arrays.toString(idList.toArray()));      System.out.println("Item Types: " + Arrays.toString(itemTypes));   }}這段代碼工作得很好,因為它能夠通過getIDList()和getItemArray()方法檢索和打印 ArrayList 和 String 數組,這些方法在ABCRentals類中指定:ABCRentals.javapublic class ABCRentals implements Inventory{   private List<Integer> idNumbers = new ArrayList<Integer>();   private List<Item> items = new ArrayList<Item>();   private List<Integer> rentedItems = new ArrayList<Integer>();   private String[] itemTypes2;   public ABCRentals() { }   public List<Integer> getIDList() {      return idNumbers;   }   public List<Item> getItemList() {      return items;    }   public String[] getItemArray() {      return itemTypes2;   }   public List<Integer> getRentedList() {      return rentedItems;   }   public boolean add(Item item)   {      if (items.size() >= 300)          return false;      else      {         idNumbers.add(idNumbers.size() + 1);         items.add(item);         Object[] itemTypes = items.toArray();         itemTypes2 = new String[itemTypes.length];         int dvd = 0, f = 0, tv = 0;         for (int index = 0; index < itemTypes.length; index++)         {            String indexValue = itemTypes[index].getClass().toString().substring(6);            if (indexValue.equals("DVDPlayer"))            {              dvd++;              itemTypes2[index] = indexValue + " #" + Integer.toString(dvd);            }因此,當我嘗試從類中訪問 ArrayList 和數組的內容時Driver,它可以工作。但是,當我嘗試從任何其他類訪問 ArrayList 或數組時,無論是DVDPlayer、Furniture或Television類,我都會收到NullPointerException錯誤,因此換句話說,ArrayList 和數組不會使用類中指定的值進行更新/Driver填充與上面不同的是,該add()方法返回為空。
查看完整描述

1 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

您在 main 中調用 add() 方法,該方法實例化 itemTypes2 數組。在訪問 Furniture 類中的 itemTypes2 之前,您不會調用 add() ,因此它為 null。



查看完整回答
反對 回復 2023-08-16
  • 1 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號