Java Collections.emptyList()和Collections.EMPTY\u LIST之间有什么区别

Java Collections.emptyList()和Collections.EMPTY\u LIST之间有什么区别,java,list,collections,Java,List,Collections,在Java中,我们有和。两者具有相同的属性: 返回空列表(不可变)。此列表可序列化 那么,使用其中一种或另一种的确切区别是什么呢? Collections.EMPTY\u LIST返回旧样式的列表 Collections.emptyList()使用类型推断,因此返回 列表 Collections.emptyList()是在Java1.5中添加的,它可能总是更可取的。这样,您就不需要在代码中进行不必要的转换 Collections.emptyList()本质上是为您进行强制转换 @Suppres

在Java中,我们有和。两者具有相同的属性:

返回空列表(不可变)。此列表可序列化

那么,使用其中一种或另一种的确切区别是什么呢?

  • Collections.EMPTY\u LIST
    返回旧样式的
    列表
  • Collections.emptyList()
    使用类型推断,因此返回
    列表
Collections.emptyList()是在Java1.5中添加的,它可能总是更可取的。这样,您就不需要在代码中进行不必要的转换

Collections.emptyList()
本质上是为您进行强制转换

@SuppressWarnings(“未选中”)
公共静态最终列表emptyList(){
返回(列表)空_列表;
}

它们是绝对平等的对象

public static final List EMPTY_LIST = new EmptyList<>();

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}
public static final List EMPTY_List=new EmptyList();
公共静态最终列表emptyList(){
返回(列表)空_列表;
}

唯一的一个是
emptyList()
返回generic
List
,因此您可以将此列表分配给generic集合,而无需任何警告。

让我们访问源代码:

 public static final List EMPTY_LIST = new EmptyList<>();
public static final List EMPTY_List=new EmptyList();

@SuppressWarnings(“未选中”)
公共静态最终列表emptyList(){
返回(列表)空_列表;
}

换句话说,空列表不是类型安全的:

  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;
与之相比:

    List<String> s = Collections.emptyList();
    Set<Long> l = Collections.emptySet();
    Map<Date, String> d = Collections.emptyMap();
List s=Collections.emptyList();
Set l=Collections.emptySet();
Map d=Collections.emptyMap();

我不是100%肯定这一点,但我相信使用/返回非类型版本(EMPTY_LIST/EMPTY_SET/EMPTY_MAP)会导致编译器放弃给定调用链中的泛型类型检查。它本质上认为它已经陷入了缺乏泛型类型的旧代码中,并放弃了。
  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;
    List<String> s = Collections.emptyList();
    Set<Long> l = Collections.emptySet();
    Map<Date, String> d = Collections.emptyMap();