Skip to content
Advertisement

Why clear() on one ArrayList is clearing elements in another ArrayList?

My desired output should be:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

By creating new ArrayList object every time

List<List<Integer>> result = new ArrayList<>();

    for(int i = 1; i <= 5; ++i){

      List<Integer> list = new ArrayList<>();

      for(int j = 1; j <= i; ++j){
        list.add(j);
      }
      result.add(list);
    }
    System.out.println(result);

I am getting the desired output as
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

But, not getting same result when trying to use clear() (to avoid creating a new object in each iteration) and also the result Arraylist gets empty too when invoking clear() on list Arraylist

List<Integer> list = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();

    for(int i = 1; i <= 5; ++i){
      for(int j = 1; j <= i; ++j){
        list.add(j);
      }
      result.add(list);
      list.clear();
    }
    System.out.println(result);

I am getting the following output using clear()
[[], [], [], [], []] –> Not the output I want

How can I achieve the desired output without creating new object(ArrayList Object) everytime and using clear() or any other concept.

Are result and list ArrayList pointing to the same reference or there is some other reason for the incorrect output. Do let me know of something I am not aware of or lacking regarding ArrayList topic.

Advertisement

Answer

tl;dr

You said:

Are result and list ArrayList pointing to the same reference

Yes.

To add a copy, change this:

result.add( list );

… to this:

result.add( new ArrayList<>( list ) );

Details

You might be thinking that result.add(list); is adding the contents of list. But no, that call passes the reference (pointer, memory address) of the ArrayList object you named list. The contents of list are irrelevant to that call. Whether empty or full, the list itself, the container, is what you are passing to add.

So you are adding the very same list five times. All the elements of result point to the very same single list. If you add to the contained list, all five elements of result see that change. If you clear that added list, all five elements of result see that change, all five elements of result point to the same single now-empty list.

To add different unmodifiable lists, call List.copyOf.

result.add( List.copyOf( list ) );

To add different modifiable lists, construct new ArrayList objects. Pass an existing list to the constructor of a new list.

result.add( new ArrayList<>( list ) );
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement