HashSet 和 TreeSet 区别 、 HashSet的底层
HashSet
HashSet是依靠hash table实现的(内部实现实际上是一个HashMap)。 不保证顺序(hash无法保证顺序)。 允许null值。 因为其实现借助于hash表,所以两个元素,e1.equals(e2)
,必须也要保证 e1.hashCode() == e2.hashCode()
LinkedHashSet
LinkedHashSet继承自HashSet,不过和HashSet不同的是,它是借助于LinkedHashMap实现的(LinkedHashMap其实也继承自HashMap,但是它依靠双向链表,实现了插入顺序有序)。所以它的特性和HashSet类似,但是LinkedHashSet是有序的,因为有了链表,所以在遍历元素的时候LinkedHashSet要优于HashSet,但是在插入时,增加了维护链表的开销,所以插入性能略差于HashSet。
/** * 依靠Hash table和linked list实现的set集合,支持顺序。 * 和HashSet的区别是内部维护了一个双向链表,链表的顺序就是插入的顺序。 * 当一个元素重新插入set时,其内部顺序不受影响 */
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable
TreeSet
不同与HashSet的无序,LinkedHashSet的插入有序,TreeSet是有序的集合,其实现了SortedSet接口。TreeSet借助于TreeMap实现。Set内的元素按照 Comparable
或者 传入构造器的Comparator
的顺序排序。TreeSet不支持null元素(因为要排序嘛)。
源码分析
HashSet
HashSet的构造函数初始化,实质上底层新建了一个HashMap的对象,可以参照之前的文章JDK8 HashMap源码详解 HashMap的构造函数对照着一起看。
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
/**
* Constructs a new set containing the elements in the specified
* collection. The <tt>HashMap</tt> is created with default load factor
* (0.75) and an initial capacity sufficient to contain the elements in
* the specified collection.
*
* @param c the collection whose elements are to be placed into this set
* @throws NullPointerException if the specified collection is null
*/
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and default load factor (0.75).
*
* @param initialCapacity the initial capacity of the hash table
* @throws IllegalArgumentException if the initial capacity is less
* than zero
*/
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
到这里,并不能明确HashSet传入的数据是用什么规则去插入到HashMap的,那么开始看看HashSet的add() 方法,这里有一个静态final参数PRESENT,按照源码中的释义是一个伪值,方便映射对象关联的。
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
而这个伪值则用来在HashSet 新增时,作为底层HashMap的Value插入。到这里也不难理解为什么HashSet中的数据不能重复的原因了,存入的值,通过计算HashCode寻址,作为链表node 的属性key存入到HashMap 中去。
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
其它的一些操作也都是和HashMap中的操作存在有对应的关系,也没太多好说的,可以将HashSet中的操作方法与HashMap源码中操作的方法对照起来看。
/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
public Iterator<E> iterator() {
return map.keySet().iterator();
}
/**
* Returns the number of elements in this set (its cardinality).
*
* @return the number of elements in this set (its cardinality)
*/
public int size() {
return map.size();
}
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* Returns <tt>true</tt> if this set contains the specified element.
* More formally, returns <tt>true</tt> if and only if this set
* contains an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this set is to be tested
* @return <tt>true</tt> if this set contains the specified element
*/
public boolean contains(Object o) {
return map.containsKey(o);
}
/**
* Removes the specified element from this set if it is present.
* More formally, removes an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>,
* if this set contains such an element. Returns <tt>true</tt> if
* this set contained the element (or equivalently, if this set
* changed as a result of the call). (This set will not contain the
* element once the call returns.)
*
* @param o object to be removed from this set, if present
* @return <tt>true</tt> if the set contained the specified element
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
/**
* Removes all of the elements from this set.
* The set will be empty after this call returns.
*/
public void clear() {
map.clear();
}
还没有评论,来说两句吧...