不可变集合immutable
程序员文章站
2022-07-13 09:15:06
...
每个Guava immutable集合类的实现都拒绝null值。我们做过对Google内部代码的全面的调查,并且发现只有5%的情况下集合类允许null值,而95%的情况下都拒绝null值。万一你真的需要能接受null值的集合类,你可以考虑用Collections.unmodifiableXXX。
Immutable集合使用方法:
一个immutable集合可以有以下几种方式来创建:
1.用copyOf方法, 譬如, ImmutableSet.copyOf(set)
2.使用of方法,譬如,ImmutableSet.of("a", "b", "c")或者ImmutableMap.of("a", 1, "b", 2)
3.使用Builder类
import java.awt.Color;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* 不可变集合
*
* @author Administrator 2009-11-4 23:30:44
*/
public class Test {
public static void main(String[] args) {
//不可变list
ImmutableList<String> list = ImmutableList.of("1","2","3","7","6","5");
System.out.println("【ImmutableList】:"+list);
ImmutableSortedSet<String> listSort = ImmutableSortedSet.copyOf(list);
System.out.println("【ImmutableSortedSet】:"+listSort);
//不可变Map
ImmutableMap<String, Integer> imap = ImmutableMap.of
("1", 1,"2", 2,"3", 4);
System.out.println("【ImmutableMap】:"+imap);
ImmutableSet<String> iset = ImmutableSet.of("a","b","c");
System.out.println("【ImmutableSet】:"+iset);
ImmutableSet<Color> imColorSet =
ImmutableSet.<Color>builder()
.add(new Color(0, 255, 255))
.add(new Color(0, 191, 255))
.build();
System.out.println("【imColorSet】:"+imColorSet);
//可变map变不可变map
ImmutableMap.Builder<String, Color> ibmap = new ImmutableMap.Builder<String, Color>();
for(int i=0;i<3;i++){
ibmap.put(""+i+"", new Color(0,111,123));
}
ImmutableMap<String,Color> imaps = ibmap.build();
System.out.println("【ImmutableMap】:"+imaps);
//Lists帮助类创建list集合
List<String> list_1 = Lists.newArrayList("4","5","6");
System.out.println("【Lists】:"+list_1);
//Maps帮助类创建map集合
Map<String,Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
System.out.println("【Maps】:"+map);
//Sets帮助类创建set集合
Set<String> set = Sets.newHashSet();
set.add("1");
set.add("1");
set.add("2");
set.add("3");
System.out.println("【Sets】:"+set);
}
}