Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty list: What is the difference between Arrays.asList() and Collections.emptyList()?

Tags:

java

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?

like image 430
Jesus Zavarce Avatar asked May 20 '16 08:05

Jesus Zavarce


People also ask

What is the difference between list of () and Arrays asList ()?

List. of doesn't allow null elements while Arrays. asList allows null elements.

What is the difference between collections emptyList () and creating new instance of collection?

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.)

What is the difference between Arrays asList and ArrayList?

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.

What is Arrays asList () in Java?

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.


1 Answers

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.

like image 184
Nicolas Filotto Avatar answered Sep 19 '22 01:09

Nicolas Filotto