首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

沙丁解牛群之 Google Guava - List

2013-01-28 
沙丁解牛之 Google Guava - List先从List说起,Guava包中只有一种List,即【abstract class】ImmutableList,其

沙丁解牛之 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]}


最后,总结一下。
场景:ImmutableList的使用场景,初始化一次后就只读的场景,如缓存,系统刚启动时获取的配置参数保存等。其本质就是用集合的接口使用数组。
启示:分而治之,对于空集合、单元素集合与多元素集合,分情况来处理,这样针对特殊情况的效率更高,空间更省。
命名:我之前的静态工厂方法喜欢以fromXxx()或toXxx(),instanceof()方法,以后用ofXxx(),asXxx(),construct()来命名也未尝不可。

热点排行