How to make a new List in Java
Solution 1:
List myList = new ArrayList();
or with generics (Java 7 or later)
List<MyType> myList = new ArrayList<>();
or with generics (Old java versions)
List<MyType> myList = new ArrayList<MyType>();
Solution 2:
Additionally, if you want to create a list that has things in it (though it will be fixed size):
List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
Solution 3:
Let me summarize and add something:
JDK
1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")
Guava
1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});
Immutable List
1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder() // Guava
.add("A")
.add("B").build();
3. ImmutableList.of("A", "B"); // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C")); // Guava
Empty immutable List
1. Collections.emptyList();
2. Collections.EMPTY_LIST;
List of Characters
1. Lists.charactersOf("String") // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava
List of Integers
Ints.asList(1,2,3); // Guava
Solution 4:
In Java 8
To create a non-empty list of fixed size (operations like add, remove, etc., are not supported):
List<Integer> list = Arrays.asList(1, 2); // but, list.set(...) is supported
To create a non-empty mutable list:
List<Integer> list = new ArrayList<>(Arrays.asList(3, 4));
In Java 9
Using a new List.of(...)
static factory methods:
List<Integer> immutableList = List.of(1, 2);
List<Integer> mutableList = new ArrayList<>(List.of(3, 4));
In Java 10
Using the Local Variable Type Inference:
var list1 = List.of(1, 2);
var list2 = new ArrayList<>(List.of(3, 4));
var list3 = new ArrayList<String>();
And follow best practices...
Don't use raw types
Since Java 5, generics have been a part of the language - you should use them:
List<String> list = new ArrayList<>(); // Good, List of String
List list = new ArrayList(); // Bad, don't do that!
Program to interfaces
For example, program to the List
interface:
List<Double> list = new ArrayList<>();
Instead of:
ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!