Guava提供了很多Immutable Collection, 包括Set,Map,List等,使用起来简单方便,看看下面的例子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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} } } |