简体   繁体   English

JDK的Arrays与Guava的ImmutableList

[英]JDK's Arrays vs. Guava's ImmutableList

使用com.google.common.collect.ImmutableList.of(...)java.util.Arrays.asList(...)创建单行列表之间是否有优势?

The Arrays.asList(...) method provides a list view of the underlying array. Arrays.asList(...)方法提供了底层数组的列表视图

Integer[] numbers = {17, 42, 2001};
List<Integer> list = Arrays.asList(numbers);
System.out.println(list.get(0)); // Prints 17.
list.remove(0);  // throws.
numbers[0] = 1;
System.out.println(list.get(0)); // Prints 1.
list.set(0, 17);
System.out.println(numbers[0]);  // Prints 17.

Arrays.asList has very little to do with immutability. Arrays.asList与不变性几乎没有关系。 The returned list cannot have elements added or removed, but it can be changed, and changes change the underlying array. 返回的列表不能添加或删除元素,但可以更改它,并且更改会更改基础数组。 In fact the class of the returned list is a special one that uses the array for storage. 实际上,返回列表的类是一个使用该数组进行存储的特殊类。 It's similar to this: 它与此类似:

List<Integer> integers = new ArrayList<>();
integers.add(17);
integers.add(42);
integers.add(2001);
List<Integer> unmodifiable = Collections.unmodifiableList(integers);
unmodifiable.set(0, 1);                  // throws.
unmodifiable.remove(0);                  // throws.
unmodifiable.add(867_5309);              // throws.
integers.set(0, 1)                       // okay.
System.out.println(unmodifiable.get(0)); // Prints 1.

That is safe only if one throws the original list away, as in this map example. 只有当抛出原始列表时,这才是安全的,就像在这个地图示例中一样。 Since map goes out of scope, nothing can change the underlying map of the unmodifiable map CAPITALS . 由于map超出范围,因此无法更改不可修改地图CAPITALS的基础地图。

public static final Map<String, String> CAPITALS;
static {
    Map<String, String> map = new HashMap<>();
    map.put("USA", "Washington, DC");
    map.put("England", "London");
    // ...
    CAPITALS = Collections.unmodifiableMap(map);
}

Guava's ImmutableList creates a new copy of the data if the original data is not stored immutably itself. 如果原始数据本身不是不可存储的,那么Guava的ImmutableList会创建一个新的数据副本。 Quoting its docs : 引用其文档

It is useful to remember that ImmutableXXX.copyOf attempts to avoid copying the data when it is safe to do so — the exact details are unspecified, but the implementation is typically “smart”. 记住ImmutableXXX.copyOf在安全的情况下尝试避免复制数据是很有用的 - 具体细节未指定,但实现通常是“智能”。

So, Guava has its immutable collections independant of their origins. 因此,番石榴有其不可变的收藏品独立于它们的起源。

List<Integer> original = new ArrayList<>();
original.add(1);
original.add(2);
original.add(3);
ImmutableList<Integer> immutable = ImmutableList.copyOf(original);
immutable.set(0, 42);  // throws.
System.out.println(immutable.get(0)); // Prints 1.
original.set(0, 42);   // fine.
System.out.println(immutable.get(0)); // Prints 1.
ImmutableList<Integer> copy = ImmutableList.copyOf(immutable);
    // Shares immutable's data.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM