Arrays.asList() vs. List.of() in Java


List.of and Arrays.asList are both used to create lists in Java, but they have some differences:

1. List.of()

  • Introduced in Java 9.
  • Creates an immutable list.
  • Does not allow null elements.
  • Returns a list with a fixed size.

2. Arrays.asList()

  • Available since Java 1.2.
  • Creates a mutable list backed by an array.
  • Allows null elements.
  • The size of the list is fixed, but the elements can be changed.

Example

// Using List.of
List<String> immutableList = List.of("a", "b", "c");
// immutableList.add("d"); // This will throw UnsupportedOperationException

// Using Arrays.asList
List<String> mutableList = Arrays.asList("a", "b", "c");
mutableList.set(0, "z"); // This is allowed
// mutableList.add("d"); // This will throw UnsupportedOperationException

Similar Post: Java 9- Creating Collection using Factory Method of(…)

3. Summary

  • Use List.of for creating immutable lists with no null elements.
  • Use Arrays.asList for creating mutable lists that allow null elements but have a fixed size.

4. References

  1. Arrays.asList() – JavaDoc
  2. List.of() – JavaDoc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.