博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java之Collections工具类方法使用以及源码分析(三)
阅读量:2054 次
发布时间:2019-04-28

本文共 5092 字,大约阅读时间需要 16 分钟。

返回指定 collection 的一个动态类型安全视图。试图插入一个错误类型的元素将导致立即抛出 ClassCastException。假设在生成动态类型安全视图之前,collection 不包含任何类型不正确的元素,并且所有对该 collection 的后续访问都通过该视图进行,则可以保证 该 collection 不包含类型不正确的元素。 
    public static <E> Collection<E> checkedCollection(Collection<E> c,Class<E> type)
调用该方法时候会进行类型检查,如果类型不匹配抛出ClassCastException异常。
package com.daxin.collections;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;/** * 返回指定 collection 的一个动态类型安全视图。试图插入一个错误类型的元素将导致立即抛出 * ClassCastException。假设在生成动态类型安全视图之前,collection 不包含任何类型不正确的元素,并且所有对该 collection * 的后续访问都通过该视图进行,则可以保证 该 collection 不包含类型不正确的元素。 */public class Main10 {	public static void main(String[] args) {		ArrayList
list = new ArrayList<>(); for (int i = 1; i <= 5; i++) { list.add(i); } Collection
view = Collections.checkedCollection(list, Integer.class); System.out.println(view); view.add(11); view.add(12); view.add(13); System.out.println(view); System.out.println(list); }}
 java.util.Collections.checkedCollection(Collection<Integer>, Class<Integer>)的实现:
public static 
Collection
checkedCollection(Collection
c, Class
type) { return new CheckedCollection<>(c, type); }
 CheckedCollection的实现;
/**     * @serial include     */    static class CheckedCollection
implements Collection
, Serializable { private static final long serialVersionUID = 1578914078182001775L; final Collection
c; final Class
type; void typeCheck(Object o) { if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); } private String badElementMsg(Object o) { return "Attempt to insert " + o.getClass() + " element into collection with element type " + type; } CheckedCollection(Collection
c, Class
type) { if (c==null || type == null) throw new NullPointerException(); this.c = c; this.type = type; } public int size() { return c.size(); } public boolean isEmpty() { return c.isEmpty(); } public boolean contains(Object o) { return c.contains(o); } public Object[] toArray() { return c.toArray(); } public
T[] toArray(T[] a) { return c.toArray(a); } public String toString() { return c.toString(); } public boolean remove(Object o) { return c.remove(o); } public void clear() { c.clear(); } public boolean containsAll(Collection
coll) { return c.containsAll(coll); } public boolean removeAll(Collection
coll) { return c.removeAll(coll); } public boolean retainAll(Collection
coll) { return c.retainAll(coll); } public Iterator
iterator() { final Iterator
it = c.iterator(); return new Iterator
() { public boolean hasNext() { return it.hasNext(); } public E next() { return it.next(); } public void remove() { it.remove(); }}; } public boolean add(E e) { typeCheck(e); return c.add(e); } private E[] zeroLengthElementArray = null; // Lazily initialized private E[] zeroLengthElementArray() { return zeroLengthElementArray != null ? zeroLengthElementArray : (zeroLengthElementArray = zeroLengthArray(type)); } @SuppressWarnings("unchecked") Collection
checkedCopyOf(Collection
coll) { Object[] a = null; try { E[] z = zeroLengthElementArray(); a = coll.toArray(z); // Defend against coll violating the toArray contract if (a.getClass() != z.getClass()) a = Arrays.copyOf(a, a.length, z.getClass()); } catch (ArrayStoreException ignore) { // To get better and consistent diagnostics, // we call typeCheck explicitly on each element. // We call clone() to defend against coll retaining a // reference to the returned array and storing a bad // element into it after it has been type checked. a = coll.toArray().clone(); for (Object o : a) typeCheck(o); } // A slight abuse of the type system, but safe here. return (Collection
) Arrays.asList(a); } public boolean addAll(Collection
coll) { // Doing things this way insulates us from concurrent changes // in the contents of coll and provides all-or-nothing // semantics (which we wouldn't get if we type-checked each // element as we added it) return c.addAll(checkedCopyOf(coll)); } }
 注意查看add方法,进行了类型检查:
public boolean add(E e) {            typeCheck(e);            return c.add(e);        }
 查看typeCheck方法实现:
void typeCheck(Object o) {            if (o != null && !type.isInstance(o))                throw new ClassCastException(badElementMsg(o));        }
代码很简单,不做解释!!
 static <E> List<E>  checkedList(List<E> list, Class<E> type) 
          返回指定列表的一个动态类型安全视图。 
static <K,V> Map<K,V>  checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType) 
          返回指定映射的一个动态类型安全视图。 
static <E> Set<E>  checkedSet(Set<E> s, Class<E> type) 
          返回指定 set 的一个动态类型安全视图。 
static <K,V> SortedMap<K,V>  checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType) 
          返回指定有序映射的一个动态类型安全视图。 
static <E> SortedSet<E>  checkedSortedSet(SortedSet<E> s, Class<E> type) 
          返回指定有序 set 的一个动态类型安全视图。  
以上方法类似,也不解释了。

转载地址:http://hkjlf.baihongyu.com/

你可能感兴趣的文章
剑指offer 36.数字在排序数组中出现的次数
查看>>
剑指offer 37.数组中重复的数字
查看>>
剑指offer 38.丑数
查看>>
剑指offer 39.构建乘积数组
查看>>
剑指offer 57. 删除链表中重复的结点
查看>>
剑指offer 58. 链表中环的入口结点
查看>>
剑指offer 59. 把字符串转换成整数
查看>>
剑指offer 60. 不用加减乘除做加法
查看>>
剑指offer 61. 求1+2+3+...+n
查看>>
剑指offer 62. 孩子们的游戏
查看>>
剑指offer 63.扑克牌顺子
查看>>
剑指offer 64. 翻转单词顺序列
查看>>
剑指offer 65. 左旋转字符串
查看>>
剑指offer 66. 和为S的两个数字
查看>>
leetcode 热题 Hot 100-5. 二叉树的最大深度
查看>>
leetcode 热题 Hot 100-2. 有效的括号
查看>>
leetcode 热题 Hot 100-3. 合并两个有序链表
查看>>
leetcode 热题 Hot 100-4. 对称二叉树
查看>>
Leetcode C++《热题 Hot 100-12》226.翻转二叉树
查看>>
Leetcode C++《热题 Hot 100-13》234.回文链表
查看>>