poi*_*oae 96 java collections list
在Java中,我们有Collections.emptyList()和Collections.EMPTY_LIST.两者都具有相同的属性:
返回空列表(不可变).此列表是可序列化的.
那么使用这一个或另一个之间的确切区别是什么?
poi*_*oae 119
Collections.EMPTY_LIST 回归旧式 ListCollections.emptyList() 使用类型推断,因此返回
List<T>在Java 1.5中添加了Collections.emptyList(),它可能总是更可取.这样,您就不需要在代码中进行不必要的转换.
Collections.emptyList()本质上为你做演员.
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
Run Code Online (Sandbox Code Playgroud)
Nim*_*sky 17
让我们来源:
public static final List EMPTY_LIST = new EmptyList<>();
Run Code Online (Sandbox Code Playgroud)
和
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
Run Code Online (Sandbox Code Playgroud)
And*_*niy 13
它们绝对是平等的对象.
public static final List EMPTY_LIST = new EmptyList<>();
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
Run Code Online (Sandbox Code Playgroud)
唯一的一个是emptyList()返回泛型List<T>,因此您可以将此列表分配给泛型集合,而不会发出任何警告.
mel*_*ngs 13
换句话说,EMPTY_LIST不是类型安全的:
List list = Collections.EMPTY_LIST;
Set set = Collections.EMPTY_SET;
Map map = Collections.EMPTY_MAP;
Run Code Online (Sandbox Code Playgroud)
相比于:
List<String> s = Collections.emptyList();
Set<Long> l = Collections.emptySet();
Map<Date, String> d = Collections.emptyMap();
Run Code Online (Sandbox Code Playgroud)