Explain Codes LogoExplain Codes Logo

How to make a new List in Java

java
list-creation
java-8
best-practices
Alex KataevbyAlex Kataev·Nov 7, 2024
TLDR

Instantly create a List in Java with:

List<YourType> myList = new ArrayList<>(); // You're so type-safe, you're like an OSHA approved construction site

For a list of Strings:

List<String> myStrings = new ArrayList<>(); // No strings attached? Please, this is JAVA!

Java's Generics keep your code clear and tidy.

For a fixed-size list with known elements:

List<String> groceryList = Arrays.asList("Eggs", "Bread", "Milk"); // Get that protein and carbs!

More ways to construct Lists

Floating with the newest release? Here's how you define an immutable list using Java 9's List.of():

List<String> immutableList = List.of("Adam", "Eve"); // Not even the serpent can change this!

Need to exhibit it but don't touch policy? Create an unmodifiable view of a list:

List<String> viewOnlyList = Collections.unmodifiableList(new ArrayList<>(Arrays.asList("A", "B"))); // Look but don't touch.

In Java 10 and beyond, you can use var to infer the list type:

var modernList = new ArrayList<String>(); // I'm so 2018!

Choose the right List for your needs

  • For random access, ArrayList is your friend:
ArrayList<String> randomlyAccessible = new ArrayList<>(); // O(1) is the new O(thank goodness).
  • If you deal with frequent insertions and deletions, go with a LinkedList:
LinkedList<YourType> linkedForInsDel = new LinkedList<>(); // Say goodbye to shifting!

Lifesaver tips about Lists

To mould a copy of an existing collection, into a list:

List<YourType> carbonCopy = new ArrayList<>(sourceCollection); // Ditto I choose you!

Guava can help you generate a list from a String or Collection:

List<Character> charList = Lists.charactersOf("LifeIsShort"); // So use a library.

Cornering immutability

To guard your list against change and still keep it empty:

List<Object> myEmptyList = Collections.emptyList(); // Because I have 'nothing' to change.

Using Guava's way of achieving immutability via Builder pattern:

ImmutableList<String> freakishlyFixed = ImmutableList.builder().add("Thor").add("Odin").build(); // You can't mess with the Gods!

Modifying a List

To replace elements at a given index:

myList.set(0, "newValue"); // Index 0, your eviction notice is here!

Let the libraries lend a hand

Guava and its handy offerings for creating a List:

List<String> filmStars = Lists.newArrayList("Tom Hanks", "Leonardo Dicaprio", "Natalie Portman"); // The red carpet is ready!

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.