LinkedLists的ArrayList引用LinkedLists

kol*_*nel 0 java

我以下列方式创建了LinkedLists的arraylist:

ArrayList<LinkedList<Card>> list = new ArrayList<>(5);
Run Code Online (Sandbox Code Playgroud)

然后我需要将链接列表添加到arrayList,所以我这样做,这似乎不起作用,因为ArrayList保持为空

for (position = 0; position < list.size(); position++) {
list.add(new LinkedList<Card>());
}
Run Code Online (Sandbox Code Playgroud)

那么我通过给出LinkedLists引用手动将linkedLists添加到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);
Run Code Online (Sandbox Code Playgroud)

最后,虽然每次迭代,我需要拉出一个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);
        }
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来访问arraylist中的LinkedLists而不会丢失信息,因为我的方式不起作用.

chr*_*ke- 5

问题出在你的初始for循环中; size()返回列表中的元素数,而不是分配的容量(如果列表实现甚至有一个).拉出你5的常数,然后从常量循环0到常量.然后,只需使用get()/ set()ArrayList正常进行.

请注意,您不必"拉出"并"放回"所包含的LinkedList对象; 你可以打电话arrayList.get(linkedListNumber).offer(card);.