Type-safe, generic, empty Collections with static generics

大兔子大兔子 提交于 2019-12-22 04:04:43

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/2625579/type-safe-generic-empty-collections-with-static-generics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!