JDK源码分析之Set类详解
JDK源码分析Set类,因为Set类是经常要用到的,那我们知道JDK源码中Set类在其中不可以有相同的元素,那么判断这个元素是否相同是如何实现的呢,我们看下下面这张图:
对JDK源码分析之Set类在这张类图上,首先我们看见一个经典模式的应用,那就是适配器模式,我们把map接口的对象,包装成为了Set的接口;在代码中,我们来分析一下;
首先,我们看一下HashSet
private transient HashMap map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();
可见,他适配了HashMap,那么他的功能是如何委托给HashMap结构的呢?
public boolean add(E e) { return map.put(e, PRESENT)==null; }
在HashMap中,我们大多数时候是用value,但是在set的时候,却很好的利用了已有类HashMap,他利用了HashMap的key的唯一性来保证存储在Set中的元素的唯一性;
private static final Object PRESENT = new Object();
是这个HashMap所有key的value,他只是一个形式,而我们真正的数据是存在在key中的资源;
我们最后拿到的迭代器也是:
public Iterator iterator() { return map.keySet().iterator(); }
Map的keySet的迭代器;
同理,我们看看LinkedhashMap;
public LinkedHashSet(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor, true); } /** * Constructs a new, empty linked hash set with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity of the LinkedHashSet * @throws IllegalArgumentException if the initial capacity is less * than zero */ public LinkedHashSet(int initialCapacity) { super(initialCapacity, .75f, true); } /** * Constructs a new, empty linked hash set with the default initial * capacity (16) and load factor (0.75). */ public LinkedHashSet() { super(16, .75f, true); }
调用了父类的构造函数;构造函数如下:
HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap(initialCapacity, loadFactor); }
生出了LinkedHashMap;
同理,我们一样可见到TreeMap的实现:
private transient NavigableMap m; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();
相关推荐
hell0kitty 2020-07-28
lonesomer 2020-09-17
Locksk 2020-10-12
佛系程序员J 2020-10-10
gdb 2020-09-14
zousongshan 2020-08-10
malonely 2020-07-20
missingmuch 2020-07-19
eternityzzy 2020-07-19
wangrui0 2020-06-28
一世为白 2020-06-21
MAC2007 2020-06-16
凉白开 2020-06-17
zhangwentaohh 2020-06-14
liangston 2020-06-14
linzb 2020-06-14
89421478 2020-06-12