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)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 List which is a subclass ofAbstractImmutableList.For older version of java or if one needs a mutable
Listthe old answer still works:2011 answer
If you create a helper method, the code looks a bit nicer. For example
and then you can do (with a static import)
Why I don’t use Arrays.asList()
The comment above is also old, for java 9+ use
List.of(E...elem).