我正在尝试创建 ArrayLists 的 ArrayList。我想创建 25 个 ArrayList 并让这些 ArrayList 包含不同的值。目标是创建一个按字长排序的字典。
我的代码看起来像
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))
问题是每个列表完成后都包含相同的值。
我知道为什么会出现这个问题。 “列表”是一个 ArrayList,ArrayList 是对象,如果您编辑一个对象,那么包含该对象的所有内容都将被编辑。
为了解决我试过的问题
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”时
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
我不知道为什么...
还可能需要注意的是,stringList 包含 58110 个值。
我也不想制作 25 个不同的 ArrayList!
最佳答案
我会尝试以下操作来完成 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);
}
关于java - 如何正确创建 ArrayList 的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758449/