The simple answer
Java 9 or later:
List<String> strings = List.of("foo", "bar", "baz");
List.of(...) will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.
This does not allow null elements.
Java 8 or earlier:
List<String> strings = Arrays.asList("foo", "bar", "baz");
Arrays.asList(...) will give you a List* backed by the passed in arguments array, so it cannot change length.
But you can call List.set(...), so it's still mutable.
This does allow null elements.
*
Implementation detail: It's a private nested class inside java.util.Arrays, named ArrayList,
which is a different class from java.util.ArrayList, even though their simple names are the same.
Static import
You can make Java 8 Arrays.asList even shorter with a static import:
import static java.util.Arrays.asList;
...
List<String> strings = asList("foo", "bar", "baz");
Any modern IDE* will suggest and do this for you.
I don't recommend statically importing the List.of method as just of, because it's confusing.
*
For example, in IntelliJ IDEA you press Alt+Enter and select Static import method...
Using Streams<
answered 2010-09-09T12:33:15.437