很多人都知道HashMap, ConcurrentHashMap.但是可能对HashSet 和TreeSet 了解不多。
1. HashSet 是一个去重复的set集合
内部实现,其实很简单就是包装了一下HashMap, 主要使用到key, Value是固定的 private static final Object PRESENT = new Object();
看看基础定义:
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
/**
* 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<>();
}
再来看看add方法, 实际操作是往map里面put key和一个常量, 如果不存在那么hashMap返回值没null,
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
同理还是有remove 方法
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
相信通过上面说明,对HashSet的底层实现应该有所了解
2.TreeMap 是一个有序的Map, 很容易想到,对Key进行了排序。
看看treeMap的基础属性定义, 关键因素就是看看private transient Entry<K,V> root到底是什么了。
/**
* The comparator used to maintain order in this tree map, or
* null if it uses the natural ordering of its keys.
*
* @serial, 这个很容易想到是用来排序的
*/
private final Comparator<? super K> comparator;
// 这个是存储具体对象的数据结构
private transient Entry<K,V> root;
/**
* The number of entries in the tree
*/
private transient int size = 0;
/**
* The number of structural modifications to the tree.
*/
private transient int modCount = 0;
看到这个属性定义,可以知道,TreeMap 是一颗红黑树的实现。 红黑树是一个不完全的有序的二叉树。
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
/**
* Make a new cell with given key, value, and parent, and with
* {@code null} child links, and BLACK color.
*/
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
通过上面2个代码的查看,总结如下:
HashSet 内部是用来Hashmap的key作为set集合
TreeMap 内部使用了红黑树来实现有序。