Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-safe, generic, empty Collections with static generics

I return empty collections vs. null whenever possible. I switch between two methods for doing so using java.util.Collections:

return Collections.EMPTY_LIST;
return Collections.emptyList();

where emptyList() is supposed to be type-safe. But I recently discovered:

return Collections.<ComplexObject> emptyList();
return Collections.<ComplexObject> singletonList(new ComplexObject());

etc.

I see this method in Eclipse Package Explorer:

<clinit> () : void

but I don't see how this is done in the source code (1.5). How is this magic tomfoolerie happening!!

EDIT: How is the static Generic type accomplished?

like image 559
Droo Avatar asked Apr 12 '10 21:04

Droo


People also ask

What is difference between collection and generics in Java?

Generics is a programming tool to make class-independent tools, that are translated at compile time to class-specific ones. Collections is a set of tools that implement collections, like list and so on.

How are generics used in collections?

The generic collections are introduced in Java 5 Version. The generic collections disable the type-casting and there is no use of type-casting when it is used in generics. The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes.

What is the difference between generic and non generic?

Cost is the main difference between generic and brand name prescription drugs. Unlike brand companies, generic manufacturers compete directly on price, resulting in lower prices for consumers. Generics have saved Americans $2.2 trillion over the last decade.


2 Answers

return Collections.<ComplexObject> emptyList();

Using this will get rid of warnings from Eclipse about non-generic collections.

Having said that, a typed empty list is going to be functionally identical to an untyped empty list due to empty list being immutable and Java erasing generic types at compile time.

like image 124
Powerlord Avatar answered Sep 22 '22 14:09

Powerlord


EDIT: How is the static Generic type accomplished?

http://www.docjar.com/html/api/java/util/Collections.java.html

public class Collections {
    ...
    public static final List EMPTY_LIST = new EmptyList<Object>();
    ...
    public static final <T> List<T> emptyList() {
        return (List<T>) EMPTY_LIST;
    }
    ...
}

You can see the link for the implementation of the EmptyList class if you're curious, but for your question, it doesn't matter.

like image 26
Bert F Avatar answered Sep 21 '22 14:09

Bert F