Post

Java) List

Java) List

This post was migrated from Tistory. You can find the original here.

List

1
2
List<Integer> list = Arrays.asList(new Integer[] {1,2,3});
List<int[]> list2 = Arrays.asList(new int[]{1, 2, 3});

Similar to Stream.of, primitive-type arrays are taken as-is.

1
2
3
4
5
6
7
8
List<Integer> a1 = Arrays.asList(1,2,3);
List<Integer> a2 = List.of(1,2,3);
a1.add(4); //UnsupportedOperationException
a2.add(4); //UnsupportedOperationException

//Write it like this instead.
List<Integer> a = new ArrayList<>(Arrays.asList(1,2,3));
a.add(4);

Both create an Immutable List, and adding an element throws an exception.
This is not a compile error, so be careful when writing this kind of code.

2D array

1
2
3
4
5
6
7
8
    public static void main(String[] args) {
        List<List<Integer>> a = new ArrayList<>();
        int num = 0;
        for(int i=0; i<5; i++){
            a.add(new ArrayList<>(Arrays.asList(num++, num++, num++)));
        }
        System.out.println(a);
    }

For 2D arrays too, use List all the way down.
If you’re approaching a problem with arrays, it seems easier to just default to thinking in terms of List.

This post is licensed under CC BY-NC 4.0 by the author.