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?
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.
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.
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.
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.
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.
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