0

Here's a simple code, where I create nested ArrayList that contains ArrayList of String. I found a weird thing: when I clear the inner ArrayList, sizes of inner and outer ArrayLists decrease to 0.

public static void  main(String[] a)
{
    ArrayList<ArrayList<String>> arrayLists = new ArrayList<>();
    ArrayList<String> element = new ArrayList<>();
    element.add("1");
    element.add("2");
    arrayLists.add(element);
    System.out.println(arrayLists);

    element.clear();
    element.add("3");
    element.add("4");
    arrayLists.add(element);
    System.out.println(arrayLists);

    element.clear();
    element.add("5");
    element.add("6");
    arrayLists.add(element);
    System.out.println(arrayLists);
}

The output of that code is:

[[1, 2]]
[[3, 4], [3, 4]]
[[5, 6], [5, 6], [5, 6]]

I found out how to solve the problem and make output like:

[[1, 2]]
[[1, 2], [3, 4]]
[[1, 2], [3, 4], [5, 6]]

Instead of clearing inner ArrayList, I initialize it again. Here's the code:

public static void  main(String[] a)
    {
        ArrayList<ArrayList<String>> arrayLists = new ArrayList<>();
        ArrayList<String> element = new ArrayList<>();
        element.add("1");
        element.add("2");
        arrayLists.add(element);
        System.out.println(arrayLists);

        element = new ArrayList<>();
        element.add("3");
        element.add("4");
        arrayLists.add(element);
        System.out.println(arrayLists);

        element = new ArrayList<>();
        element.add("5");
        element.add("6");
        arrayLists.add(element);
        System.out.println(arrayLists);
    }

So the question is: is this intended to be like that (and what's the mechanism behind that) or is it a bug that needs to be reported? I've checked this code step by step using debugger, and I checked that outer ArrayList gets size 0 after element gets cleared.

Nick Pakhomov
  • 313
  • 4
  • 13
  • Yes, this is perfectly normal. You add a _reference_ to the list `element` to the outer list, not a copy. – Louis Wasserman Dec 17 '15 at 20:58
  • You may also want to read [What is the difference between a variable, object, and reference?](http://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference) – Sotirios Delimanolis Dec 17 '15 at 21:00

0 Answers0