Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would someone use Collections.emptyList in java? [duplicate]

Possible Duplicate:
Collections.emptyList() vs. new instance

I was trying to understand the difference between create a new instance of a list using:

new ArrayList<X>

and

Collections.emptyList();

As I understood, the later returns an immutable list. That means that it is not possible to add,delete, or modify it. I want to know why one would create and immutable emptyList ? what is the use? thanks

like image 389
Hossein Avatar asked Sep 26 '12 08:09

Hossein


People also ask

When would you use collections emptyList?

Use Collections. emptyList() if you want to make sure that the returned list is never modified.

How do I check if a list is empty or null?

The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

How do you return an empty ArrayList in Java?

Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns. Return Value: This method does not return any value.


1 Answers

Being immutable allows for reusable instances.

Collections.emptyList will always return the exact same singleton instance.

This is very efficient.

In addition to that, immutable data can be safely shared between threads, and is guaranteed to avoid weird side-effects due to coding errors. For that reason it makes defensive copies unnecessary, too.

like image 87
Thilo Avatar answered Sep 29 '22 15:09

Thilo