您的位置:首页 > 编程语言 > Go语言

Google Guava学习之Immutable Collection

2011-06-08 16:49 627 查看
以前为了实现传递不可变容器,我们常要做预防性拷贝,实现起来很繁琐。

Guava的Immutable Collection实现了只读容器。当你试图调用改变容器的操作时,就会有相应的异常抛出。

以下代码以ImmutableMap和ImmutableSet做为例子。

import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;

public class TryImmutableMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("abc", "def");
map.put("def", "efg");
// a immutable map is cloned from a regular map.
ImmutableMap<String, String> aImmutalbeMap = ImmutableSortedMap.<String, String>copyOf(map);
//aImmutalbeMap.put("tgh", "ihg"); // Exception!! You can't change it.
//aImmutalbeMap.clear();			// Exception!! You can't change it.
//aImmutalbeMap.remove("abc");		// Exception!! You can't change it.
System.out.println(aImmutalbeMap.containsKey("abc")); // this line is ok.
// for immutable set
ImmutableSet<String> immutableSet = ImmutableSortedSet.<String>of("abc", "def", "efg");
System.out.println(immutableSet); // output: [abc, def, efg]
// for small immutable map
ImmutableMap<String, String> immutableMap = ImmutableSortedMap.<String, String>of("abc", "def");
System.out.println(immutableMap); // output: {abc=def}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: