public static void usingCopyOf(){
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
ImmutableSet<Integer> immutableSet = ImmutableSet.copyOf(set);
//这里是不支持添加元素的
/*immutableSet.add(4);
Set<Integer> addOne = new HashSet<>();
addOne.add(5);
immutableSet.addAll(addOne);*/
}
public static void usingOf(){
ImmutableSet<Integer> ofSet = ImmutableSet.of(1,2,3,4,5,6,7);
System.out.println(ofSet);
}
public static void usingBuilder(){
ImmutableSet<Integer> builderSet = ImmutableSet.<Integer>builder()
.add(1)
.add(2)
.build();
System.out.println(builderSet);
}
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<E>();
}
可变集合类型 | 可变集合源:JDK or Guava | Guava不可变集合 |
---|---|---|
Collection | JDK | ImmutableCollection |
List | JDK | ImmutableList |
Set | JDK | ImmutableSet |
SortedSet/NavigableSet | JDK | ImmutableSortedSet |
Map | JDK | ImmutableMap |
SortedMap | JDK | ImmutableSortedMap |
Multiset | Guava | ImmutableMultiset |
SortedMultiset | Guava | ImmutableSortedMultiset |
Multimap | Guava | ImmutableMultimap |
ListMultimap | Guava | ImmutableListMultimap |
SetMultimap | Guava | ImmutableSetMultimap |
BiMap | Guava | ImmutableBiMap |
ClassToInstanceMap | Guava | ImmutableClassToInstanceMap |
Table | Guava | ImmutableTable |
接下来就是了解这些集合啦