0.1) 本文描述转自 core java volume 1, 源代码为原创,旨在理解 java集合——视图与包装器 的相关知识;
0.2) for full source code , please visit https://github.com/pacosonTang/core-java-volume/blob/master/chapter13/ViewAndWrapper.java
1.1)通过使用视图可以获得其他的实现了集合接口和映射表接口的对象;
Card[] cardDeck = new Card[25];
List cardList = Arrays.asList(cardDeck); (数组转List视图对象)
对以上代码的分析(Analysis):
List<String> names = Arrays.asList<"a", "b", "c">;
List<String> settings = Collections.nCopies(100, "DEFAULT");
干货问题:(如何区分 Collection 和 Collections)
Anotation) Collections 类包含很多实用方法, 这些方法的参数和返回值都是集合。 不要将 Collection接口 和 Collections 包装类 混淆起来了;
1.3.3)调用以下代码: Collections.singleton(anObject); 则返回一个视图对象。 这个对象实现了Set 接口。 返回的对象实现了一个不可修改的单元素集, 而不需要付出建立数据结构的 开销。 singletonList 和 singletonMap 方法类似;
1.4) 子范围
1.4.1)可以为很多集合建立子范围视图;
如, List g2 = staff.subList(10,20); 从列表staff 中取出 第10个~第19个元素;(第一个 索引包含在内,第二个索引不包含在内)
1.4.3)对于有序集合映射表, 可以使用 排序顺序而不是元素位置建立子范围。
1.4.3.1)SortedSet 接口说明了3个方法:
SortedSet<E> subSet(E from ,E to)
SortedSet<E> headSet(E to)
SortedSet<E> tailSet(E from)
SortedSet<E> subMap(E from ,E to)
SortedSet<E> headMap(E to)
SortedSet<E> tailMap(E from)
NabigableSet subSet(E from, boolean fromInclusive, E to, boolean toInclusive);
NabigableSet headSet(E to, boolean toInclusive);
NabigableSet tailSet(E from, boolean fromInclusive);
Collections.unmodifiableCollection
Collections.unmodifiableList
Collections.unmodifiableSet
Collections.unmodifiableSortedSet
Collections.unmodifiableMap
Collections.unmodifiableSortedMap
每个方法都定义于一个接口。如, Collections.unmodifiableList 与 ArrayList、LinkedList 或者任何实现了 List接口的其他类一起协同工作;
1.5.1荔枝):
List<String> staff = new LinkedList<>();
lookAt(Collections.unmodifiableList(staff)); // 返回一个不可修改视图, 传递给 loopAt方法;
Warning)
1.6)同步视图
Map<String, Employee> map = Collections.synchronizedMap(new HashMap<String, Employee>());
1.7)检查视图
ArrayList<String> strings = new ArrayList<>();
ArrayList rawList = strings;
rawList.add(new Date());//
这个错误的 add 命令在运行时检测不到。 相反,只有在 调用 get方法, 并将其 转换为 String 时,这个类才会抛出一个异常;
1.7.2)解决方法:检查视图可以探测到这类问题。下面定义了一个安全列表:
List safeString = Collections.checkedList(strings, String.class);
视图的add 方法将检测 插入的对象是否属于给定的类。 如果不属于给定的类, 就立即抛出一个 ClassCastException。 这样做的好处是错误可以在正确的位置得以报告:
ArrayList rawList = safeString;
rawList.add(new Date()); // checked list chrows a ClassCastException