开发者

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?


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.


<clinit> is the static initializer block. It is a block of code which is executed exactly once (when the class is loaded).

So, instead of writing

class  A  {
   static int x = 5;
}

One can write:

class A {
   static int x;

   static {  // static initializer starts
      x = 5; 
   }
}

These two classes are equivalent. Inside a static initializer block one can place arbitrary code and thus initialize static fields with the results of complicated calculations.


<clinit> is the name of the method into which the class initialization code is collected by during compilation. (That is, all of the code inside static {} blocks, and the initializers of static members, in source code order.)

It has nothing to do with explicit type parameters in method invocations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜