具有静态泛型的类型安全,通用,空集合

Dro*_*roo 10 java collections

我尽可能返回空集合与null.我使用java.util.Collections在两种方法之间切换:

return Collections.EMPTY_LIST;
return Collections.emptyList();
Run Code Online (Sandbox Code Playgroud)

哪里emptyList()应该是类型安全的.但我最近发现:

return Collections.<ComplexObject> emptyList();
return Collections.<ComplexObject> singletonList(new ComplexObject());
Run Code Online (Sandbox Code Playgroud)

等等

我在Eclipse Package Explorer中看到了这个方法:

<clinit> () : void
Run Code Online (Sandbox Code Playgroud)

但我不知道在源代码(1.5)中是如何完成的.怎么这个神奇的tomfoolerie发生了!

编辑:如何完成静态通用类型?

Pow*_*ord 16

return Collections.<ComplexObject> emptyList();
Run Code Online (Sandbox Code Playgroud)

使用它将消除Eclipse关于非泛型集合的警告.

话虽如此,由于空列表是不可变的并且Java在编译时擦除泛型类型,因此类型化的空列表将在功能上与无类型的空列表相同.


Ber*_*t F 9

编辑:如何完成静态通用类型?

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;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果你很好奇,你可以看到实现EmptyList类的链接,但是对于你的问题,它并不重要.