2013-11-22 52 views
0

我創建LinkedLists的ArrayList以下方式:的ArrayList LinkedLists參考LinkedLists

ArrayList<LinkedList<Card>> list = new ArrayList<>(5); 

然後我需要讓我這樣做,這似乎不是linkedlists添加到ArrayList爲ArrayList的工作

 LinkedList<Card> temp_list0 = new LinkedList<Card>(); 
     LinkedList<Card> temp_list1 = new LinkedList<Card>(); 
     LinkedList<Card> temp_list2 = new LinkedList<Card>(); 
     LinkedList<Card> temp_list3 = new LinkedList<Card>(); 
     LinkedList<Card> temp_list4 = new LinkedList<Card>(); 
     list.add(temp_list0); 
     list.add(temp_list1); 
     list.add(temp_list2); 
     list.add(temp_list3); 
     list.add(temp_list4); 
:通過給linkedLists引用保持空

for (position = 0; position < list.size(); position++) { 
list.add(new LinkedList<Card>()); 
} 

於是我手動添加linkedLists到ArrayList

最後,雖然每次迭代,我需要拔出一個LinkedLists來添加一些東西,然後把它放回到ArrayList中的位置,但是通過這樣做,我失去了對LinkedList的引用,因此信息是丟失

for (position = 0; position < deck.length; position++) { 
      scan = (deck[position]).getValue(); 
      temp_list = list.get(scan); 
      temp_list.offer(deck[position]); 
      list.add(scan, temp_list); 
     } 

有沒有更好的方式來訪問arraylist中的LinkedList而不會丟失信息,因爲我的方式不起作用。

回答

5

問題出在您的初始for循環中; size()返回列表中元素的數量,而不是分配的容量(如果列表實現甚至有一個)。取出你的5爲一個常量,並從0循環到常量。然後在ArrayList上正常使用get()/set()

請注意,您不必「拉出」並「放回」包含的對象LinkedList;您可以致電arrayList.get(linkedListNumber).offer(card);

+0

所以當我做arrayList.get(linkedListNumber).offer(card);它知道把它放回數組列表嗎? – kolonel

+0

@kimos您需要了解Java引用的工作原理。沒有涉及「迴歸」;你檢索LinkedList,然後對它進行操作(比如插入一個對象)。 'LinkedList'仍然在'ArrayList'的右邊,直到你告訴'ArrayList'來替換或刪除它。 – chrylis

+0

我看得很好,非常感謝。 – kolonel

相關問題