CSchulz
CSchulz

Reputation: 11020

Object without any content/empty Object

while developing I was trying to return an empty List.

public Collection<?> getElements() {
    // return elements
}

I searched for an easy way, my first idea was to create for example an ArrayList without any elements and return it. Like the following example:

public Collection<?> getElements() {
    return new ArrayList<?>();
}

For me it is too much overhead for an empty list.

Upvotes: 0

Views: 107

Answers (1)

CSchulz
CSchulz

Reputation: 11020

There is a really simple solution for the above described "problem":

public Collection<?> getElements() {
    return Collections.EMPTY_LIST;
}

That returns an empty list.

Notice:
It returns an immutable object! You can use it only, if you need an object, which isn't editable.

Type-safety
In the case you want to get a type-safe list you should use the following example [1]:

List<String> s = Collections.emptyList();

Three kinds of interfaces are supported:

  • List:

    List l = Collections.EMPTY_LIST;
    List<String> s = Collections.emptyList();
    
  • Map:

    Map m = Collections.EMPTY_MAP;
    Map<String> ms = Collections.emptyMap();
    
  • Set:

    Set s = Collections.EMPTY_SET;
    Set<String> ss = Collections.emptySet();
    

Notice:

Implementations of this method need not create a separate XXX object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

Upvotes: 2

Related Questions