gpt4 book ai didi

java - 没有任何内容的对象/空对象

转载 作者:行者123 更新时间:2023-12-02 07:36:04 26 4
gpt4 key购买 nike

在开发时,我试图返回一个空的列表

public Collection<?> getElements() {
// return elements
}

我寻找一种简单的方法,我的第一个想法是创建一个没有任何元素的ArrayList并返回它。就像下面的例子:

public Collection<?> getElements() {
return new ArrayList<?>();
}

对我来说,空列表的开销太大了。

最佳答案

对于上述“问题”有一个非常简单的解决方案:

public Collection<?> getElements() {
return Collections.EMPTY_LIST;
}

这会返回一个空列表。

注意:
它返回一个不可变对象!仅当您需要一个不可编辑的对象时才可以使用它。

类型安全
如果您想获得类型安全列表,您应该使用以下示例 [ 1 ]:

List<String> s = Collections.emptyList();

支持三种接口(interface):

  • 列表:

    List l = Collections.EMPTY_LIST;
    List<String> s = Collections.emptyList();
  • map :

    Map m = Collections.EMPTY_MAP;
    Map<String> ms = Collections.emptyMap();
  • 设置:

    Set s = Collections.EMPTY_SET;
    Set<String> ss = Collections.emptySet();

注意:

Implementations of this method need not create a separate XXX object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

关于java - 没有任何内容的对象/空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12214059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com