Java 实例 - 只读集合


以下实例演示了如何使用 Collection 类的 Collections.unmodifiableList() 方法来设置集合为只读:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.Collections;
  9. import java.util.HashMap;
  10. import java.util.HashSet;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Set;
  14.  
  15. public class Main {
  16. public static void main(String[] argv)
  17. throws Exception {
  18. List stuff = Arrays.asList(new String[] { "a", "b" });
  19. List list = new ArrayList(stuff);
  20. list = Collections.unmodifiableList(list);
  21. try {
  22. list.set(0, "new value");
  23. }
  24. catch (UnsupportedOperationException e) {
  25. }
  26. Set set = new HashSet(stuff);
  27. set = Collections.unmodifiableSet(set);
  28. Map map = new HashMap();
  29. map = Collections.unmodifiableMap(map);
  30. System.out.println("集合现在是只读");
  31. }
  32. }

以上代码运行输出结果为:

  1. 集合现在是只读