【问题标题】:For Google Guava ImmutableLists is creating a copy of Collections.EMPTY_LIST equivalent to ImmutableList.of()?对于 Google Guava,ImmutableLists 正在创建相当于 ImmutableList.of() 的 Collections.EMPTY_LIST 的副本?
【发布时间】:2014-01-09 17:22:36
【问题描述】:

其中哪一个更受欢迎?

private static ImmutableList<Airline> sAirlines = 
                          ImmutableList.copyOf(Collections.EMPTY_LIST);

private static ImmutableList<Airline> sAirlines = ImmutableList.of();

【问题讨论】:

    标签: java collections guava


    【解决方案1】:

    如果你想要一个空的不可变列表,那么你应该使用第二种方法。因为,对于一个空集合,copyOf 方法无论如何都会在内部调用of() 方法。

    copyOf(Collection&lt;? extends E&gt;) 方法内部使用以下方法:

    static <E> ImmutableList<E> asImmutableList(Object[] elements) {
        switch (elements.length) {
          case 0:
            return of();
          case 1:
            @SuppressWarnings("unchecked") // collection had only Es in it
            ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
            return list;
          default:
            return construct(elements);
        }
      }
    

    如您所见,对于0 的长度,它只是调用of() 方法。

    【讨论】:

    • of() 也更可取,因为如果您以后从空更改为具有一个或多个元素,只需在括号之间添加这些元素即可。
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多