All That Dev

new ArrayList() or List.of()

November 8, 2024 | by Cícero Fabio

allthaedev.com.backgroud

In Java 11, when deciding how to initialize a list attribute, you have two options that you’ve presented: using new ArrayList<>() or List.of(). Each has its own use case, so let’s break down the differences:

1. Using new ArrayList<>()

var variable = new ArrayList<>();
  • Mutable: This creates a mutable list, which means you can add, remove, or modify elements after its creation.
  • Performance: It has a time complexity of O(1) for adding elements (on average), making it efficient if you plan to modify the list frequently.
  • Use Case: Ideal for scenarios where you need to dynamically change the contents of the list.

2. Using List.of()

var variable = List.of();
  • Immutable: This creates an immutable list, meaning you cannot add or remove elements after its creation. Any attempt to modify the list will result in UnsupportedOperationException.
  • Performance: It can be more memory efficient in certain scenarios since it doesn’t have the overhead of dynamic resizing.
  • Use Case: Best for cases where you want to ensure that the list’s contents should not change after initialization, such as representing a fixed set of items.

Final Thoughts

  • If you need a list that will change over time (adding/removing items), use new ArrayList<>().
  • If you want to create a list that should remain constant and won’t be modified, use List.of().

Choose whether you need mutability or immutability for your specific use case.

RELATED POSTS

View all

view all