Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a two-dimensional List statically?

How can I initialize a multidimensional List statically?

This works:

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

But I'd like to init the list with some static lists like: (1,2,3), (4,5,6) and (7,8,9)

like image 596
cody Avatar asked Jun 03 '11 21:06

cody


People also ask

How do you initialize a two-dimensional array?

Here is how we can initialize a 2-dimensional array in Java. int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.

How do you initialize a 2D string?

The quickest way I can think of is to use Arrays. fill(Object[], Object) like so, String[][] board1 = new String[10][10]; for (String[] row : board1) { Arrays. fill(row, "-"); } System.


1 Answers

This is an old answer, but things have changed a bit. For java 9+ this can be done using the List.of() method which returns an immutable collections.

import java.util.List;

List<List<Integer>> list = List.of(
                               List.of(1, 2, 3),
                               List.of(4, 5, 6),
                               List.of(7, 8, 9)
                           );

For older version of java or if one needs a mutable List the old answer still works:

2011 answer

If you create a helper method, the code looks a bit nicer. For example

public class Collections {
    public static <T> List<T> asList(T ... items) {
        List<T> list = new ArrayList<T>();
        for (T item : items) {
            list.add(item);
        }

        return list;
    }
}

and then you can do (with a static import)

List<List<Integer>> list = asList(
                             asList(1,2,3),
                             asList(4,5,6),
                             asList(7,8,9),
                           );

Why I don't use Arrays.asList()

Arrays.asList() returns a class of type java.util.Arrays.ArrayList (it's an inner class of Arrays). The problem I've found is that it's VERY easy to think that one is using a java.lang.ArrayList, but their implementation are very, very different.

like image 52
Augusto Avatar answered Sep 22 '22 06:09

Augusto