Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arraylist not work as expected

Tags:

java

arraylist

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

like image 456
while true Avatar asked May 06 '26 20:05

while true


1 Answers

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);
like image 180
Krypton Avatar answered May 09 '26 11:05

Krypton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!