Java Nested ArrayList not Adding Correctly

user11485720 :

I have been trying out nested arrayList methods. I have a problem.

public static void main(String[] args) {
    List<List<Integer>> list = new ArrayList<>();
    List<Integer> subList = new ArrayList<Integer>(){{
        add(1);
        add(2);
    }};
    list.add(subList);
    subList.clear();
    subList.add(3);
    subList.add(4);
    list.add(subList);
    System.out.println(list);
}

This does not give expected output. The result is

[[3, 4], [3, 4]]

and not [[1, 2], [3, 4]]

What is wrong with my Code.

EDIT: I have a few more issues on the code. Should I create a new quetsion or add it here.

BlackPearl :

I would advice you against using double brace initialization new ArrayList<Integer>{{ }} as it is kind of an anti-pattern and also creates anonymous inner classes.

As for the error, you should initialize a new list instead of clear()

public static void main(String[] args) {
    List<List<Integer>> list = new ArrayList<>();
    List<Integer> subList = new ArrayList<>();
    subList.add(1);
    subList.add(2);
    list.add(subList);
    subList = new ArrayList<>();
    subList.add(3);
    subList.add(4);
    list.add(subList);
    System.out.println(list);
}

Calling clear does not change the reference to the ArrayList, and will point to the same object. You should create a new reference by calling subList = new ArrayList<>()

A good read about the ill-effects of double brace initialization

https://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/

EDIT: As @NoDataFound suggests, if you are using Java 8+, the process of creating a List can be much more simplified.

If you are using Java 8, you can create a list by using

List<Integer> subList = Arrays.asList(1, 2);

If you are using Java 9+, you can make use of

List<Integer> subList = List.of(1, 2);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71972&siteId=1