HashSet是借助于HashMap来进行实现的,而LinkedHashSet是基于LinkedHashMap进行实现的。
1、LinkedHashSet的继承体系
LinkedHashSet是继承HashSet类,并实现了Set接口。因此具有HashSet类的一切特性。
public class LinkedHashSet <E >
extends HashSet <E >
implements Set <E >, Cloneable , java .io .Serializable
2、LinkedHashSet的构造函数
public LinkedHashSet (int initialCapacity, float loadFactor) {
super (initialCapacity, loadFactor, true );
}
public LinkedHashSet (int initialCapacity) {
super (initialCapacity, .75 f, true );
}
public LinkedHashSet () {
super (16 , .75 f, true );
}
public LinkedHashSet (Collection<? extends E> c) {
super (Math.max(2 *c.size(), 11 ), .75 f, true );
addAll(c);
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
上面就是LinkedHashSet的几种构造函数,这几种构造函数都是调用的父类HashSet的如下这个构造函数:
/*
Constructs a new , empty linked hash set . (This package private
constructor is only used by LinkedHashSet.)
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
从如上的构造函数,可以得到,LinkedHashSet是借助于LinkedHashMap来实现的哈。
LinkedHashSet并没有重写HashSet的任何方法,因此,当我们了解了HashSet内部的实现之后,我们也就了解了LinkedHashSet的内部实现。
小结
关于LinkedHashSet的内部实现,我们只需要记住一点:是继承的HashSet类,基于LinkedHashMap来实现的即可。