i have 2 arraylist
ArrayList<List<Integer>> main = new ArrayList<>();
ArrayList<Integer> sub=new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
sub.clear();
sub.add(5);
sub.add(6);
sub.add(7);
main.add(sub);
now i expect main to be
what i expect main-->[[1,2],[5,6,7]] ;
but really main-->[[567],[567]];
i think sub array share reference ..so how can i make
main as [[1,2],[5,6,7]
i can't create sub1 ,sub2,...because actually i do this inside huge loop
5 Answers 5
You were modifying the list and adding it one more time, so that's why [567] appeared twice. I suggest you change code as following:
ArrayList<List<Integer>> main = new ArrayList<>();
ArrayList<Integer> sub = new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
sub = new ArrayList<>();
sub.add(5);
sub.add(6);
sub.add(7);
main.add(sub);
Comments
You are referring to same instance
sub.add(1);
sub.add(2);
main.add(sub);
sub.clear(); // you are clearing same instance you added to `main` list
you need to create new instance
You need
ArrayList<Integer> sub1 = new ArrayList<>();
sub1.add(1);
sub1.add(2);
main.add(sub1);
ArrayList<Integer> sub2 = new ArrayList<>();
sub2.add(10);
sub2.add(20);
main.add(sub2);
Comments
Adding to an ArrayList using the .add function, adds the reference of the same memory address onto the ArrayList.
So in your solution, a reference pointing to what sub was pointing to was added in the ArrayList. This reference internally pointed to the same location.
Now when you cleared 'sub', the actual data got cleared and as there was only one copy of the data(with two references pointing to it), it cleared.
Now when you added to sub back , it got added to the same memory location which was pointed by both the references. Hence you see its copy in main.
Hope you understood.
Comments
you can clone the same object like this:
public static void main(String[] args) {
ArrayList<List<Integer>> main = new ArrayList<List<Integer>>();
ArrayList<Integer> sub=new ArrayList<Integer>();
sub.add(1);
sub.add(2);
main.add(sub);
sub=(ArrayList<Integer>) sub.clone();// clone here
sub.clear();
System.out.println("sub = "+sub);
System.out.println("main = "+main);
sub.add(5);
sub.add(6);
sub.add(7);
main.add(sub);
System.out.println("sub = "+sub);
System.out.println("main = "+main);
}
output :
sub = []
main = [[1, 2]]
sub = [5, 6, 7]
main = [[1, 2], [5, 6, 7]]
Comments
Assuming your Integer's are already in a collection that is the basis of your "Big Loop":
ArrayList<List<Integer> main_list = new ArrayList<>();
Collection<Collection<Integer>> mySubs = xxxx;
for (Collection<Integer> group : mySubs){
List<Integer> sub = new ArrayList<>(group);
main_list.add(sub)
}
All of the Collection classes have constructors that can take other Collection's
If you don't have an existing collection to start with, then you'll just need to use sub.clone().clear() or sub = new ArrayList<>()
ArrayListinstead of clearing the one.clonefor the same check out my answer