[英]Type-safe, generic, empty Collections with static generics
I return empty collections vs. null whenever possible. 我尽可能返回空集合与null。 I switch between two methods for doing so using java.util.Collections :
我使用java.util.Collections在两种方法之间切换:
return Collections.EMPTY_LIST;
return Collections.emptyList();
where emptyList()
is supposed to be type-safe. 其中
emptyList()
应该是类型安全的。 But I recently discovered: 但我最近发现:
return Collections.<ComplexObject> emptyList();
return Collections.<ComplexObject> singletonList(new ComplexObject());
etc. 等等
I see this method in Eclipse Package Explorer: 我在Eclipse Package Explorer中看到了这个方法:
<clinit> () : void
but I don't see how this is done in the source code (1.5). 但我不知道在源代码(1.5)中是如何完成的。 How is this magic tomfoolerie happening!!
怎么这个神奇的tomfoolerie发生了!
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. 使用它将消除Eclipse关于非泛型集合的警告。
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. 话虽如此,由于空列表是不可变的并且Java在编译时擦除泛型类型,因此类型化的空列表将在功能上与无类型的空列表相同。
EDIT: How is the static Generic type accomplished?
编辑:如何完成静态通用类型?
http://www.docjar.com/html/api/java/util/Collections.java.html 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. 如果你很好奇,你可以看到实现EmptyList类的链接,但是对于你的问题,它并不重要。
<clinit>
is the static initializer block. <clinit>
是静态初始化程序块。 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. <clinit>
是编译期间收集类初始化代码的方法的名称。 (That is, all of the code inside static {}
blocks, and the initializers of static members, in source code order.) (也就是说,
static {}
块内的所有代码,以及源代码顺序中静态成员的初始化器。)
It has nothing to do with explicit type parameters in method invocations. 它与方法调用中的显式类型参数无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.