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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With