沙丁解牛之 Google Guava - List
先从List说起,Guava包中只有一种List,即【abstract class】ImmutableList,其有四个实现类:EmptyImmutableList,SingletonImmutableList,RegularImmutableList,【abstract class】ImmutableAsList,如下图(红色背景属于JDK,黄色背景属于Guava。点开大图清晰,弱问,怎么把图100%显示?):
public abstract class com.google.common.collect.ImmutableCollection:所有Immutable集合的抽象父类,不允许null元素。
顾名思义,ImmutableCollection是不可变集合,根据《Effective Java》中的原则xx,不可变有很多优点。JDK的Collections中有一系列static unmodifiable*()方法,这些方法包装的集合也可以防止被执行修改操作,但是这种革命意志坚决不动摇是假的或者是不纯粹的,是伪装的投降主义,一个好同志要坚决抵制,例如:
@Testpublic void test() {// 构造of() 适用于从几个已知元素ImmutableList<Integer> iList = ImmutableList.of(1, 2);System.out.println(iList);// [1, 2]// copyOf() 适用于从一个已知集合or数组构造iList = ImmutableList.copyOf(iList);System.out.println(iList);// [1, 2]iList = ImmutableList.copyOf(new Integer[] { 1, 2, 3, 4 });System.out.println(iList);// [1, 2, 3, 4]// 单元素集合的对象是SingletonImmutableListiList = ImmutableList.of(6);System.out.println(iList);// [6]// 空集合的对象是静态变量EmptyImmutableList.INSTANCEImmutableList<Integer> iList1 = ImmutableList.of();ImmutableList<Integer> iList2 = ImmutableList.of();System.out.println(iList1 == iList2);// true// builder()适用于元素不定的集合构造,但每一次add都是一次arrayCopy,效率不高Builder<Integer> builder = ImmutableList.builder();builder.add(1);builder.add(2, 3);builder.addAll(iList);iList = builder.build();System.out.println(iList);// [1, 2, 3, 6]}