如何正确创建ArrayLists的ArrayList? [英] How to correctly create an ArrayList of ArrayLists?
问题描述
我正在尝试创建一个ArrayLists的ArrayList.我想创建25个ArrayList,并让这些ArrayList拥有不同的值.目的是创建按字长排序的字典.
I am trying to create an ArrayList of ArrayLists. I want to create 25 ArrayLists and have those ArrayList hold different values. The goal being to create a sorted dictionary by word length.
我的代码看起来像
for(int i = 0; i < 25; i++)
list2D.add(list);
for(int i = 0; i < stringList; i++)
list2D.get(stringList.get(i).length()).add(stringList.get(i))
问题在于,每个列表在完成后都包含相同的值.
The problem is that every list contains the same values after it finishes.
我知道为什么会这样. 列表"是一个ArrayList,ArrayList是对象,如果您编辑一个对象,则包含该对象的所有内容都会被编辑.
I know why the problem is happening. "list" is an ArrayList, ArrayList's are objects and if you edit an object then everything containing that object will be edited.
要解决我尝试过的问题
for(int i = 0; i < 25; i++){
list = new ArrayList<String>();
for(int i2 = 0; i2 < stringList.size(); i2++){
if(stringList.get(i).length() == i)
list.add(stringList.get(i2));
}
list2D.add(list);
}
但是当我测试我的"list2D"
But when I test my "list2D"
for(int i = 0; i < 25; i++)
System.out.print(list2D.get(i).size()+" ");
我知道
0 0 0 0 0 58110 0 58110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 58110 0 58110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
我不知道为什么...
and I have no idea why...
另外,可能有必要注意stringList包含58110个值.
Also it might be relevant to note that stringList contains 58110 values.
我也不想创建25个不同的ArrayList!
Also I don't want to have to make 25 different ArrayLists!
推荐答案
我将尝试以下操作对stringList进行一次遍历
I would try the following to do a single pass of the stringList
List<List<String>> dict = new ArrayList<>();
for(string s: stringsList) {
int len = s.length();
// add new array lists as required, could be any length, assuming << 100
while(dict.size() <= len) dict.add(new ArrayList<String>());
// add the string to the right list.
dict.get(len).add(s);
}
这篇关于如何正确创建ArrayLists的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!