In some program as following:
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp=new ArrayList<Integer>();
I want to add temp into result, if I use
result.add(new ArrayList<Integer>(temp));
then the final output is correct, but if I use
result.add(temp);
then my final output is wrong. Why? Thanks for the help!
This, result.add(new ArrayList<Integer>(temp))
, and this, result.add(temp)
will both produce the same contents in result
Without understanding clearly the desired output, I cannot see what is actually wrong with the code.
Further, it is better practice to refer to the ArrayList as a List
on the left side and use the <>
diamond on the right. Make your coding easier and clearer:
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
temp.add(1);
temp.add(2);
result.add(temp);
System.out.println("Result: " + result);
The output is exactly as specified and is a List<List<Integer>>
:
Result: [[1, 2]]
When you call:
result.add(new ArrayList<Integer>(temp));
temp
is copied into a new ArrayList and the end-result will contain the "untouched" copy.
By calling:
result.add(temp)
you're adding temp
itself to the result
so the actions you'll preform later-on on temp
will be reflected in result
(that's the unwanted behavior you described).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.