Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Collections.emptyList() and Collections.EMPTY_LIST

In Java, we have Collections.emptyList() and Collections.EMPTY_LIST. Both have the same property:

Returns the empty list (immutable). This list is serializable.

So what is the exact difference between using the one or the other?

like image 694
poitroae Avatar asked Feb 14 '13 08:02

poitroae


People also ask

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

emptyList is immutable so there is a difference between the two versions so you have to consider users of the returned value. Returning new ArrayList<Foo> always creates a new instance of the object so it has a very slight extra cost associated with it which may give you a reason to use Collections.

What is collections emptyList?

The emptyList() method of Java Collections class is used to get a List that has no elements. These empty list are immutable in nature.

How do you empty a list in Java?

clear() method removes all of the elements from this list. The list will be empty after this call returns.


4 Answers

  • Collections.EMPTY_LIST returns an old-style List
  • Collections.emptyList() uses type-inference and therefore returns List<T>

Collections.emptyList() was added in Java 1.5 and it is probably always preferable. This way, you don't need to unnecessarily cast around within your code.

Collections.emptyList() intrinsically does the cast for you.

@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}
like image 113
poitroae Avatar answered Oct 16 '22 08:10

poitroae


Lets get to the source :

 public static final List EMPTY_LIST = new EmptyList<>();

and

@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}
like image 44
NimChimpsky Avatar answered Oct 16 '22 07:10

NimChimpsky


They are absolutely equal objects.

public static final List EMPTY_LIST = new EmptyList<>();

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

The only one is that emptyList() returns generic List<T>, so you can assign this list to generic collection without any warnings.

like image 14
Andremoniy Avatar answered Oct 16 '22 07:10

Andremoniy


In other words, EMPTY_LIST is not type safe:

  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;

As compared to:

    List<String> s = Collections.emptyList();
    Set<Long> l = Collections.emptySet();
    Map<Date, String> d = Collections.emptyMap();
like image 14
mel3kings Avatar answered Oct 16 '22 07:10

mel3kings