Google Guava学习之Immutable Collection
2011-06-08 16:49
627 查看
以前为了实现传递不可变容器,我们常要做预防性拷贝,实现起来很繁琐。
Guava的Immutable Collection实现了只读容器。当你试图调用改变容器的操作时,就会有相应的异常抛出。
以下代码以ImmutableMap和ImmutableSet做为例子。
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} } }
相关文章推荐
- Guava学习笔记:Google Guava 类库简介
- [置顶] Guava学习之Immutable集合
- Google的Guava它Collection升华
- Guava学习笔记:Immutable(不可变)集合
- 集合框架学习之Guava Collection
- Google Guava学习(10)-Guava字符串工具Joiner
- Google Guava学习之Constraint
- Guava学习笔记:Google Guava 类库简介
- Guava学习笔记:Google Guava 类库简介
- [Google Guava]学习--新集合类型Multimap
- Guava学习笔记:Immutable(不可变)集合
- 【Google Guava 学习笔记 二】关于Optional,避免null对你的摧残
- Guava学习笔记:Google Guava 类库简介
- Guava学习笔记:Google Guava 类库简介
- 集合框架学习之Guava Collection
- Google Guava学习之Table
- Guava学习笔记:Google Guava 类库简介
- Google Guava学习(1)-Guava Optional类
- Google Guava学习(2)-Guava Preconditions类
- Google Guava学习(10)-Guava字符串工具Spiltter