Java集合学习笔记II
Set接口
Set是Collection接口的另一个重要的子接口,set接口之中没有提供额外的方法
Set集合中,不允许添加相同的元素(比较的是equals方法)
Set接口中的实现类
Set接口最为常用的实现类为HashSet、除此之外较为常见的还有LinkedHashSet以及子接口SortedSet等。其中SortedSet接口中的元素是有序
HashSet
HashSet是Set接口中最为常用的实现类。HashSet接口维护的元素是无序的、不可重复(可以为Null)、HashSet线程不安全。
//HashSet类中的属性与空参构造器
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object();
public HashSet() {
this.map = new HashMap();
}
从上述代码中我们可以发现,HashSet底层维护了一个HashMap对于集合中的元素进行维护。因此这里我们就暂时不对HashSet的底层结构进行整理。
HashSet常用方法(方法摘自https://www.apiref.com/java11-zh/index.html):
boolean | add(E e) | 如果指定的元素尚不存在,则将其添加到此集合中。 |
---|---|---|
void | clear() | 从该集中删除所有元素。 |
Object | clone() | 返回此 HashSet 实例的浅表副本:未克隆元素本身。 |
boolean | contains(Object o) | 如果此set包含指定的元素,则返回 true 。 |
boolean | isEmpty() | 如果此集合不包含任何元素,则返回 true 。 |
Iterator<E> | iterator() | 返回此set中元素的迭代器。 |
boolean | remove(Object o) | 如果存在,则从该集合中移除指定的元素。 |
int | size() | 返回此集合中的元素数(基数)。 |
Spliterator<E> | spliterator() | 返回一个可分割迭代器 |
TreeSet
SortedSet的主要实现类,与HashSet相似,一样维护了TreeMap对数据进行维护。
public TreeSet() {
this((NavigableMap)(new TreeMap()));
}
TreeSet因其内部元素有序的特性,加入了一些特有的方法,例如
E | first() | 返回此集合中当前的第一个(最低)元素。 |
---|---|---|
E | floor(E e) | 返回此set中小于或等于给定元素的最大元素,如果没有这样的元素,则 null 。 |
E | last() | 返回此集合中当前的最后一个(最高)元素。 |
---|---|---|
E | lower(E e) | 返回此集合中的最大元素严格小于给定元素,如果没有这样的元素,则 null 。 |
SortedSet<E> | subSet(E fromElement, E toElement) | 返回此set的部分视图,其元素范围从 fromElement (含)到 toElement (独占)。 |
---|---|---|
SortedSet<E> | tailSet(E fromElement) | 返回此set的部分视图,其元素大于或等于 fromElement 。 |
Map接口
Map接口是Iterator接口中的另一个主要实现类。维护并存储具有映射关系的键值对。Map中的kv可以存放各种类型的数据。(是否可以存放null需要根据具体实现类进行判断)。Map中的key不可重复,Map中的对象需要重写hashCode与equals方法。
Map接口的主要实现类有HashMap、LinkedHashMap与TreeMap。其中HashMap最为常见。
HashMap
HashMap是Map接口中使用频率最高的实现类。HashMap中Key与Value都可以存放null值。
HashMap中的主要方法:
boolean | containsKey(Object key) | 如果此映射包含指定键的映射,则返回 true 。 |
---|---|---|
boolean | containsValue(Object value) | 如果此映射将一个或多个键映射到指定值,则返回 true 。 |
Set<Map.Entry<K,V>> | entrySet() | 返回此映射中包含的映射的Set视图。 |
V | get(Object key) | 返回指定键映射到的值,如果此映射不包含键的映射,则返回 null 。 |
boolean | isEmpty() | 如果此映射不包含键 - 值映射,则返回 true 。 |
Set<K> | keySet() | 返回此映射中包含的键的Set视图。` |
V | put(K key, V value) | 将指定的值与此映射中的指定键相关联。 |
---|---|---|
void | putAll(Map<? extends K,? extends V> m) | 将指定映射中的所有映射复制到此映射。 |
V | remove(Object key) | 从此映射中删除指定键的映射(如果存在)。 |
int | size() | 返回此映射中键 - 值映射的数量。 |
Collection<V> | values() | 返回此映射中包含的值的集合 |
HashMap集合的遍历
//先获取key的集合,再通过key获取value的值
Set<String> keys = map.keySet();
for (String key:keys) {
System.out.println(key + map.get(key));
}
//获取所有的entrySet集合,通过增强for循环进行遍历(也可以获取迭代器进行遍历)
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for(Map.Entry<String,Integer> elem : entries){
System.out.println(elem.getKey() + elem.getValue());
}
//获取值(v)的集合
Collection<Integer> values = map.values();
for (int val : values){
System.out.println(val);
}
HashMap的底层实现:
数组+链表+红黑
底层部分成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始容量——16
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认加载因子
static final int TREEIFY_THRESHOLD = 8; // 链表长度大于此值时,转化为红黑树
static final int UNTREEIFY_THRESHOLD = 6; // 红黑树节点数量小于此值时,转化为链表
static final int MIN_TREEIFY_CAPACITY = 64; // 单个链表转化为树时,整个表的最小容量
int size; //容量
内部类:定义了储存元素的Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //哈希值
final K key; //key
V value; //value
Node<K,V> next; //指针
//构造器
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
构造器与相关CRUD公有方法的实现:
//空参构造器 (所有的相关参数均为默认值)
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//添加操作 // 底层调用非公有putVal方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0) //如果当前哈希表为空,创建一个哈希表
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); //如果数组将要放置的索引的位置为空,直接放在数组中
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p; //如果p(索引)位置上的Node Key与插入的key相同,插入替换该元素
else if (p instanceof TreeNode) //判断当前节点是否为红黑树的节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //调用putTreeVal方法,这里不进一步展开
else { //否则,说明当前节点指向一个链表
for (int binCount = 0; ; ++binCount) { //遍历此链表,判断是否有重复的key
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null); //没有重复的key 直接插入到链表的尾部
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash); //判断是否需要转为红黑树
break;
}
if (e.hash == hash && //如果找相同的,则直接替换V
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//判断是否需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//删除的方法(remove)
//调用removeNode方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
//removeNode方法
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 && //判断如果hash表为空,直接返回null
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v; //前半部分目的为再表中找到要删除的节点
if (p.hash == hash && // 直接在数组找到目标节点
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) { // 开始遍历
if (p instanceof TreeNode) //判断是否为树结构
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else { //继续遍历找到目标节点
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//删除目标节点的方法
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) //树结点的删除
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) //头节点的删除
tab[index] = node.next;
else //链表中间节点的删除
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
//查询操作(get方法)
//底层调用非公有方法getNode
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value; //getNode方法若返回空,返回Null,否则返回Value
}
//非公有方法getNode
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 && //先判断哈希表或者key对应的索引是否为空,为空直接返回null
(first = tab[(n - 1) & hash]) != null) { //判断数组索引上的节点是否为想要的节点
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first; // 是,返回该节点
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key); //判断是否为树结构(是,调用getTreeNode方法)
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) //遍历查找链表中的节点
return e;
} while ((e = e.next) != null);
}
}
return null;
}
HashMap的扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; //获取扩容前的数组大小
int oldThr = threshold; //扩容临界值
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) { //如果超过最大容量
threshold = Integer.MAX_VALUE;
return oldTab; //不进行扩容
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && //不超临界值,大于初始容量 扩容为原来的两倍
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr; //新的容量设为指定的初始值
else { // zero initial threshold signifies using defaults //新的数组容量设为初始值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor; //重新计算扩容的临界值
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; //创建一个新的数组
table = newTab;
if (oldTab != null) { //当旧的数组部位空的时候,遍历原来的数组,移至新的数组
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) { //取出表中的元素
oldTab[j] = null;
if (e.next == null) //如果原表索引位置只有一个节点,直接插入到新的数组中
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode) //如果原来为树结构
((TreeNode<K,V>)e).split(this, newTab, j, oldCap); //分离树结构
else { // preserve order //处理链表
Node<K,V> loHead = null, loTail = null; //原来数组某一索引j的元素,若重新计算hash则仅可能放入到新数组[j]/[j+oldCap]
Node<K,V> hiHead = null, hiTail = null; //的位置
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) { //判断hash值多的哪一位是否为0
if (loTail == null) //对低位链表进行操作
loHead = e;
else
loTail.next = e;
loTail = e;
}
else { //为一的情况
if (hiTail == null) //对高位链表进行操作
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead; //将低位链表查到新数组索引为j的位置
}
if (hiTail != null) { // 将高为链表插入到[j+oldCap]的位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
计算Hash值的方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
} //获取key的hash值,再与其高16位的Hash值进行一个异或操作,得到新的Hash值
//充分利用高低位,减少不同key,hash过后值冲突的情况
总结:
实例化一个HashMap,会根据参数初始化初始容量以及负载因子。当加入第一个k-v的时候,系统会创建一个长度为初始容量的Node数组。添加对象时,系统会根据key的Hash值,去寻找其在Node数组中的我位置,如果当前位置没有元素则添加成功,否则将会判断是否重复,如果不重复,将会添加到当前索引节点为头节点的链表中(需要遍历判断k是否相等。)如果链表长度过长,则当前链表会转变为红黑树。
通过红黑树解决Hash冲突的好处:
用链表解决Hash冲突,机端情况下,HashMap,的CRUD效率将降至O(n)(遍历链表所有元素),采用树的结构,效率将改进至O(logn).
为什么每次扩容都是原来的二倍:
尽量减少Hash冲突
尽量减少扩容后元素的移动
TreeMap
TreeMap底层使用红黑树存储数据。因此其在存储K-V对的时候,需要根据key进行排序。相较于HashMap,TreeMap中也提供了一些基于其有序特性的相关方法。例如:
部分特有方法
返回最小(大)键
Map.Entry<K,V> | firstEntry() | 返回与此映射中的最小键关联的键 - 值映射,如果映射为空,则 null 。 |
---|---|---|
K | firstKey() | 返回此映射中当前的第一个(最低)键。 |
返回大于(小于)某一个Key的元素
Map.Entry<K,V> | floorEntry(K key) | 返回与小于或等于给定键的最大键关联的键 - 值映射,如果没有此键,则 null 。 |
---|---|---|
K | floorKey(K key) | 返回小于或等于给定键的最大键,如果没有这样的键,则 null |
返回相关范围的k-v集合
SortedMap<K,V> | tailMap(K fromKey) | 返回此映射的部分视图,其键大于或等于 fromKey 。 |
---|---|---|
NavigableMap<K,V> | tailMap(K fromKey, boolean inclusive) | 返回此映射的部分视图,其键大于(或等于,如果 inclusive 为true) fromKey 。 |
TreeMap的定制排序
//TreeMap定制排序
//自定义实现降序排序
TreeMap<Integer, String> map1 = new TreeMap<Integer, String>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
map1.put(1,"a");
map1.put(2,"b");
System.out.println(map1.firstKey()); //2