我不想将新项目添加到现有列表中,而是想为新项目创建一个新列表。例如,
最终输出:[[情况1,这是方法A],[情况2,这是方法A]]
但是,我的代码输出是
最终输出:[[case1,这是方法 A,case2,这是方法 A],[case1,这是方法 A,case2,这是方法 A]]
我不太确定我哪里出错了。 任何帮助将不胜感激!谢谢!
下面是我的代码。
static List<List<String>> list = new ArrayList<>();
static ArrayList<String> temp = new ArrayList<>();
public static void main(String[] args) {
for (int q = 1; q < 3; q++) {
switch (q) {
case 1:
temp.add("case1");
methodA();
list.add(temp);
break;
case 2:
temp.add("case2");
methodA();
list.add(temp);
break;
}
}
System.out.println("FINAL OUTPUT:" + list);
}
private static void methodA() {
temp.add("this is method A");
}
最佳答案
由于 clear()
影响已添加到最终结果(在上一次迭代中)的列表,因此您必须在清除它 (2) 之前制作一个副本 (1)。
list.add(new ArrayList<>(temp)); // 1
temp.clear(); // 2
让我们将 3 个重复行移出 switch
。
switch (q) {
case 1:
temp.add("case1");
break;
case 2:
temp.add("case2");
break;
}
methodA();
list.add(new ArrayList<>(temp));
temp.clear();
关于java - 数组列表的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51572045/