How to make a new List in Java
Instantly create a List in Java with:
For a list of Strings:
Java's Generics keep your code clear and tidy.
For a fixed-size list with known elements:
More ways to construct Lists
Floating with the newest release? Here's how you define an immutable list using Java 9's List.of()
:
Need to exhibit it but don't touch policy? Create an unmodifiable view of a list:
In Java 10 and beyond, you can use var
to infer the list type:
Choose the right List for your needs
- For random access,
ArrayList
is your friend:
- If you deal with frequent insertions and deletions, go with a
LinkedList
:
Lifesaver tips about Lists
To mould a copy of an existing collection, into a list:
Guava can help you generate a list from a String or Collection:
Cornering immutability
To guard your list against change and still keep it empty:
Using Guava's way of achieving immutability via Builder pattern:
Modifying a List
To replace elements at a given index:
Let the libraries lend a hand
Guava and its handy offerings for creating a List:
Best practices for working with Lists
Always interact with the List
interface for flexibility and read as Generics to keep your code safe from runtime surprises.
Was this article helpful?