If i need an empty list, I could use
Arrays.asList()
or
Collections.emptyList()
What is the difference between these two calls? Which one should I use?
List. of doesn't allow null elements while Arrays. asList allows null elements.
The main difference is that Collections. emptyList() returns an immutable list, i.e., a list to which you cannot add elements. (Same applies to the List. of() introduced in Java 9.)
asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.
The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.
Collections.emptyList()
is your best option because it reuses an object instead of creating a new object as it will be the case with Arrays.asList()
.
NB: Collections.emptyList()
returns an immutable object so if you intend to modify it later in your code you will need to create your list explicitly instead because you will face the same issue with Arrays.asList()
as it is immutable too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With