首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ArrayList of LinkedLists reference LinkedLists

ArrayList of LinkedLists reference LinkedLists
EN

Stack Overflow用户
提问于 2013-11-22 16:50:09
回答 1查看 91关注 0票数 0

我以以下方式创建了一个LinkedLists数组:

代码语言:javascript
复制
ArrayList<LinkedList<Card>> list = new ArrayList<>(5);

然后,我需要将链接列表添加到arrayList中,所以我这样做了,因为ArrayList仍然是空的,这似乎不起作用。

代码语言:javascript
复制
for (position = 0; position < list.size(); position++) {
list.add(new LinkedList<Card>());
}

然后,通过提供linkedLists引用,手动将arrayList添加到LinkedLists中:

代码语言:javascript
复制
        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来添加一些东西,然后把它放回数组列表中的位置,但是这样做,我就失去了对LinkedList的引用,因此信息就丢失了。

代码语言:javascript
复制
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);
        }

是否有更好的方法访问数组列表中的LinkedLists而不丢失信息,因为我的方法不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-22 16:51:25

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

请注意,您不必“取出”和“放回”包含的LinkedList对象;只需调用arrayList.get(linkedListNumber).offer(card);即可。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20150170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档