Java8前時代
在Java8版本以前,建立一個只讀不可變的集合,先要初始化,然後塞資料,然後置為只讀:
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
set = Collections.unmodifiableSet(set);
複製程式碼
上面的方式佔用太多行,能不能用單行表示式呢?用如下方式:
Set<String> set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));
Set<String> set = Collections.unmodifiableSet(new HashSet<String>() {{
add("a"); add("b"); add("c");
}});
複製程式碼
Java8
在Java8中可以用流的方法建立,具體可以看之前的一篇文章Java8新特性系列(Stream),實現方法如下:
Set<String> set = Collections.unmodifiableSet(Stream.of("a", "b", "c").collect(toSet()));
複製程式碼
Java9
Java9中引入了很多方便的API,Convenience Factory Methods for Collections,即集合工廠方法,官方Feature,上述的實現中Java9中有如下實現方式:
Set<String> set = Collections.unmodifiableSet(new HashSet<String>() {{
add("a"); add("b"); add("c");
}});
複製程式碼
也可以用如下方式:
Set<String> set = Set.of("a", "b", "c");
複製程式碼
Java9中List
提供了一系列類似的方法:
/**
* Returns an immutable list containing zero elements.
* @since 9
*/
static <E> List<E> of() {
return ImmutableCollections.List0.instance();
}
/**
* Returns an immutable list containing one element.
* @since 9
*/
static <E> List<E> of(E e1) {
return new ImmutableCollections.List1<>(e1);
}
/**
* Returns an immutable list containing one element.
* @since 9
*/
static <E> List<E> of(E e1) {
return new ImmutableCollections.List1<>(e1);
}
/**
* Returns an immutable list containing three elements.
* @since 9
*/
static <E> List<E> of(E e1, E e2, E e3) {
return new ImmutableCollections.ListN<>(e1, e2, e3);
}
...
/**
* Returns an immutable list containing ten elements.
* @since 9
*/
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return new ImmutableCollections.ListN<>(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
}
@SafeVarargs
@SuppressWarnings("varargs")
static <E> List<E> of(E... elements) {
switch (elements.length) { // implicit null check of elements
case 0:
return ImmutableCollections.List0.instance();
case 1:
return new ImmutableCollections.List1<>(elements[0]);
case 2:
return new ImmutableCollections.List2<>(elements[0], elements[1]);
default:
return new ImmutableCollections.ListN<>(elements);
}
}
複製程式碼
Java9中Set、Map都有類似的方法,建立只讀不可變的集合:
Set.of()
...
Map.of()
Map.of(k1, v1)
Map.of(k1, v1, k2, v2)
Map.of(k1, v1, k2, v2, k3, v3)
...
Map.ofEntries(Map.Entry<K,V>...)
Map.Entry<K,V> entry(K k, V v)
Map.ofEntries(
entry(k1, v1),
entry(k2, v2),
entry(k3, v3),
// ...
entry(kn, vn)
);
複製程式碼