对于Google Guava,ImmutableLists正在创建一个与ImmutableList.of()等效的Collections.EMPTY_LIST副本?

kur*_*ryt -1 java collections guava

其中哪一个更受欢迎?

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

private static ImmutableList<Airline> sAirlines = ImmutableList.of();
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 9

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

copyOf(Collection<? extends E>)方法内部使用以下方法:

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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,对于长度0,它只是调用of()方法.