The container class list of Java cannot access the list object correctly during the iteration process

Zhang Jiuzhang 2022-06-24 07:53:11 阅读数:357

containerclasslistjavaaccess

I'm brushing today LeetCode When , Wrote such a piece of code ( part ):

ArrayList<List<Integer>> retArray = new ArrayList<>();
LinkedList<Integer> ret = new LinkedList<>();
while(True){
while(True){
ret.addLast(p.val);
}
if(True){
if(True){
retArray.add(ret);
}
}else{
ret.remove();
}
}

Here, at the time of output , Although logically correct , But the output is

[[][]]

Rewrite the code like this :

ArrayList<List<Integer>> retArray = new ArrayList<>();
LinkedList<Integer> ret = new LinkedList<>();
while(True){
while(True){
ret.addLast(p.val);
}
if(True){
if(True){
retArray.add(new LinkedList<>(ret));
}
}else{
ret.remove();
}
}

Or rewrite it as :

ArrayList<List<Integer>> retArray = new ArrayList<>();
LinkedList<Integer> ret = new LinkedList<>();
while(True){
while(True){
ret.addLast(p.val);
}
if(True){
if(True){
LinkedList<Integer> test = (LinkedList<Integer>)ret.clone();
retArray.add(test);
}
}else{
ret.remove();
}
}

The root cause of this situation is , In the method retArray.add(ret) in , We created a global res Objects and retArray object , because java It's value passing, not reference passing , therefore retArray.add(ret) when ,path In fact, they are the same object , All point to the same address .
Experiments can be done as follows :

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
List<List<Integer>> res = new ArrayList<>();
System.out.println(res);
res.add(list);
list.add(50);
res.add(list);
System.out.println(res);

The output is as follows :

[]
[[1, 2, 3, 50], [1, 2, 3, 50]]

In later code ,ret.remove(); This operation will LinkedList One by one , This causes the final output to be null .

copyright:author[Zhang Jiuzhang],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240325432887.html