• JDK源码分析之Set类详解——适配器模式的应用


    JDK源码中Set类是我们开发过程中经常用到的,那么本文将会向你介绍JDK源码中Set类的一些构造,使我们在编程中高效的应用。

    AD:

    JDK源码分析Set类,因为Set类是经常要用到的,那我们知道JDK源码中Set类在其中不可以有相同的元素,那么判断这个元素是否相同是如何实现的呢,我们看下下面这张图:

    JDK源码分析之Set类图  

    对JDK源码分析之Set类在这张类图上,首先我们看见一个经典模式的应用,那就是适配器模式,我们把map接口的对象,包装成为了Set的接口;在代码中,我们来分析一下;

    首先,我们看一下HashSet

    1. private transient HashMap map;  
    2.  
    3.    // Dummy value to associate with an Object in the backing Map  
    4.    private static final Object PRESENT = new Object(); 

    可见,他适配了HashMap,那么他的功能是如何委托给HashMap结构的呢?

    1. public boolean add(E e) {  
    2.    return map.put(e, PRESENT)==null;  
    3.    } 

    在HashMap中,我们大多数时候是用value,但是在set的时候,却很好的利用了已有类HashMap,他利用了HashMap的key的唯一性来保证存储在Set中的元素的唯一性;

    private static final Object PRESENT = new Object();

    是这个HashMap所有key的value,他只是一个形式,而我们真正的数据是存在在key中的资源;

    我们最后拿到的迭代器也是:

    1. public Iterator iterator() {  
    2.   return map.keySet().iterator();  
    3.   } 

    Map的keySet的迭代器;

    同理,我们看看LinkedhashMap;

    1. public LinkedHashSet(int initialCapacity, float loadFactor) {  
    2.        super(initialCapacity, loadFactor, true);  
    3.    }  
    4.  
    5.    /**  
    6.     * Constructs a new, empty linked hash set with the specified initial  
    7.     * capacity and the default load factor (0.75).  
    8.     *  
    9.     * @param   initialCapacity   the initial capacity of the LinkedHashSet  
    10.     * @throws  IllegalArgumentException if the initial capacity is less  
    11.     *              than zero  
    12.     */ 
    13.    public LinkedHashSet(int initialCapacity) {  
    14.        super(initialCapacity, .75f, true);  
    15.    }  
    16.  
    17.    /**  
    18.     * Constructs a new, empty linked hash set with the default initial  
    19.     * capacity (16) and load factor (0.75).  
    20.     */ 
    21.    public LinkedHashSet() {  
    22.        super(16, .75f, true);  
    23.    } 

    调用了父类的构造函数;构造函数如下:

    1. HashSet(int initialCapacity, float loadFactor, boolean dummy) {  
    2.  map = new LinkedHashMap(initialCapacity, loadFactor);  
    3.  } 

    生出了LinkedHashMap;

    同理,我们一样可见到TreeMap的实现:

    1. private transient NavigableMap m;  
    2.  
    3. // Dummy value to associate with an Object in the backing Map  
    4. private static final Object PRESENT = new Object(); 

    更多的,我们也可以理解他是一种桥接模式的一种变形,不过我想从意义上,我更愿意相信其是适配器的应用;

    对JDK源码分析之Set类到这里,希望对你有帮助。

  • 相关阅读:
    go 资料
    BW:如何加载和生成自定义的层次结构,在不使用平面文件的SAP业务信息仓库
    权限变量 --转载
    BW CUBE 数据的聚集和压缩
    BW基于ALE的主数据增量机制分析
    SAP-GR/IR的理解
    SDN论坛看到BW的问题及相关解答
    Step by step Process of creating APD
    处理链方式执行APD处理
    BW标准数据源初始化设置
  • 原文地址:https://www.cnblogs.com/daichangya/p/12960055.html
Copyright © 2020-2023  润新知