输出错误 这里我有 3 个列表“chkptPrice”、“fuelNeeded”和“motherList”。因此,在循环中,我将新元素添加到“chkptPrice”和“fuelNeeded”,然后将两个列表添加到“motherList”。当循环第一次运行时,一切都很顺利,但之后当我使用“chkptPrice”和“fuelNeeded”向“motherList”添加新元素时,整个列表将被相同的元素替换,并且元素会重复。
System.out.println("Enter the test cases");
int tess = scan.nextInt();
scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println("Enter the number of checkpoints: ");
int checkpt = scan.nextInt();
scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
List<List<Integer>> motherList = new ArrayList<List<Integer>>();
List<Integer> chkptPrice = new ArrayList<Integer>();
List<Integer> fuelNeeded = new ArrayList<Integer>();
for(int i=0; i<tess; i++)
{
chkptPrice.clear();
fuelNeeded.clear();
String[] price = scan.nextLine().split(" ");
for(int j=0; j<checkpt; j++)
{
int intPrice = Integer.parseInt(price[j]);
chkptPrice.add(intPrice);
}
String[] fueldist = scan.nextLine().split(" ");
for(int j=0; j<checkpt; j++)
{
int intDist = Integer.parseInt(fueldist[j]);
fuelNeeded.add(intDist);
}
System.out.println("Elements in chktPrice: "+chkptPrice);
System.out.println("Elements in fuelNeeded: "+fuelNeeded);
motherList.add(chkptPrice);
motherList.add(fuelNeeded);
System.out.println("Elements of motherList: "+motherList);
}
====输入======
2
2
1 3
4 6
4 9
1 8
====输出======
{第一个循环}
Elements in chktPrice: [1, 3]
Elements in fuelNeeded: [4, 6]
Elements of motherList: [[1, 3], [4, 6]]
{第二个循环}
Elements in chktPrice: [4, 9]
Elements in fuelNeeded: [1, 8]
Elements of motherList: [[4, 9], [1, 8], [4, 9], [1, 8]]
motherList 元素应该是
[[1, 3], [4, 6], [4, 9], [1, 8]]
最佳答案
当您调用clear
时,您并不是在创建新列表,而是删除已存在列表的内容(您清空了先前迭代中已添加的列表的内容)。
然后,当您在当前迭代中再次将它们添加到 motherList 时,您只需添加两个指向相同旧对象的新引用(因此最终有 4 个引用指向两个对象)。
要解决此问题,您必须重新初始化列表,而不是使用 clear
。
chkptPrice.clear(); -> chkptPrice = new LinkedList<>();
fuelNeeded.clear(); -> fuelNeeded = new LinkedList<>();
关于java - 向 List 添加新元素会替换之前的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440419/