![](/img/trans.png)
[英]Why does adding a new element to an array list replace all the previous elements with the new one?
[英]Adding new elements to List replaces the previous elements
輸出錯誤輸出這里有3個列表“ chkptPrice”,“ fuelNeeded”和“ motherList”。 因此,在循環中,我將新元素添加到“ chkptPrice”和“ fuelNeeded”中,然后在此之后,將兩個列表都添加到“ motherList”中。 第一次運行Loop時,一切正常,但是之后,當我使用“ chkptPrice”和“ fuelNeeded”向“ motherList”添加新元素時,整個List會被相同的元素替換,並且重復這些元素。
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<>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.