[英]What is the difference between Collections.emptyList() and Collections.EMPTY_LIST
In Java, we have Collections.emptyList() and Collections.EMPTY_LIST . 在Java中,我们有Collections.emptyList()和Collections.EMPTY_LIST 。 Both have the same property:
两者都具有相同的属性:
Returns the empty list (immutable).
返回空列表(不可变)。 This list is serializable.
此列表是可序列化的。
So what is the exact difference between using the one or the other? 那么使用这一个或另一个之间的确切区别是什么?
Collections.EMPTY_LIST
returns an old-style List
Collections.EMPTY_LIST
返回旧式List
Collections.emptyList()
uses type-inference and therefore returns List<T>
Collections.emptyList()
使用类型推断,因此返回List<T>
Collections.emptyList() was added in Java 1.5 and it is probably always preferable . 在Java 1.5中添加了Collections.emptyList(),它可能总是更可取 。 This way, you don't need to unnecessarily cast around within your code.
这样,您就不需要在代码中进行不必要的转换。
Collections.emptyList()
intrinsically does the cast for you . Collections.emptyList()
本质上为你做演员。
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
Lets get to the source : 让我们来源:
public static final List EMPTY_LIST = new EmptyList<>();
and 和
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
They are absolutely equal objects. 它们绝对是平等的对象。
public static final List EMPTY_LIST = new EmptyList<>();
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
The only one is that emptyList()
returns generic List<T>
, so you can assign this list to generic collection without any warnings. 唯一的一个是
emptyList()
返回通用List<T>
,因此您可以将此列表分配给泛型集合,而不会发出任何警告。
In other words, EMPTY_LIST is not type safe: 换句话说,EMPTY_LIST不是类型安全的:
List list = Collections.EMPTY_LIST;
Set set = Collections.EMPTY_SET;
Map map = Collections.EMPTY_MAP;
As compared to: 相比于:
List<String> s = Collections.emptyList();
Set<Long> l = Collections.emptySet();
Map<Date, String> d = Collections.emptyMap();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.