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
Use Collections. emptyList() if you want to make sure that the returned list is never modified.
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.
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.
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.
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