深入理解Java集合框架
Java集合实现了常用数据结构,是开发中最常用的功能之一。
Java集合主要的功能由三个接口:List、Set、Queue以及Collection组成。
常见接口:
- List : 列表,顺序存储,可重复
- Set :集合,与数学中的集合有同样的特性:元素不能重复
- Queue:队列
- Collection:所有Java集合的接口,定义了“集合”的常用接口
结构结构
常用集合
- ArrayList 一种可以动态增长或缩减的索引集合,底层通过
Ojbect[]
数组实现,默认容量为10,在使用是如果确定仓储的数据容量应尽量为其初始化以避免动态扩容时的拷贝开销 - LinkedList 高效插入删除的有序序列,是双向链表,使用node节点存储数据;它又实现了双向队列
- ArrayDeque 用循环数组实现的双端队列
- HashSet 一种没有元素的无序集合
- TreeSet 有序的集合
- LinkedHashSet 能记录插入顺序的集合
- PriorityQueue 优先队列
- HashMap 存储键/值关系数据
- TreeMap 能根据键的值排序的键/值关系数据数据
- LinkedHashMap 可以键/值记录添加顺序
Java集合框架结构
如何选用这些数据结构
通常选用基于我们需要处理的数据的特点以及集合的特点来确定的。
如果只是简单存储一组数据,如几个用户的信息,这时选用ArrayList是比较合适的,如果数据频繁添加、删除那选用LinkedList是比较合适的。
如果想存储一组数据且不希望重复,那选用Set集合合适的。
如果希望添加插入的数据能够有顺序,那选择TreeSet是比较合适的,当然TreeMap也可以。
使用
ArrayList
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListTest {
@Test
public void test() throws Exception {
ArrayList<Integer> list = new ArrayList<>();
// 更推荐使用面向接口的使用方式,方便以后切换
//List<Integer> list = new ArrayList<>();
list.add(3);
list.add(2);
list.add(1);
// for打印
for (Integer e : list) {
System.out.println(e);
}
// 排序 小->大
Collections.sort(list);
System.out.println(list); // 打印
// 排序 大->小
List<Integer> list2 = Arrays.asList(2,3,5);
Collections.sort(list2,(a,b)->b-a);
// 排序 大->小
list2.sort((a, b) -> b - a); // 功能同上
System.out.println(list2);
}
}
// 输出
3
2
1
[1, 2, 3]
[5, 3, 2]
Set
import org.junit.Test;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class SetTest {
static class User {
String name;
int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return Objects.hashCode(this.name);
}
// 逻辑根据名字判断User是否相同
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof User) {
User u = (User) obj;
return this.name != null
? this.name.equals(u.name)
: u.name == null;
}
return false;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Test
public void test() throws Exception {
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.add(3);
System.out.println(set);
// 添加重复的人
Set<User> users = new HashSet<>();
users.add(new User("张三",18));
// 重复,不进行添加
users.add(new User("张三",19));
users.add(new User("李四",20));
for (User u : users) {
System.out.println(u);
}
}
}
// 输出
[1, 2, 3]
User{ name='null', age=18}
User{ name='李四', age=20}
HashMap
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
@Test
public void test() throws Exception {
HashMap<String,String> map = new HashMap<>();
map.put("张三","110");
map.put("李四","119");
map.put("王二","120");
// 键重复,更新原有的
map.put("王二","139");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+" ---> "+entry.getValue());
}
}
}
// 打印
李四 ---> 119
张三 ---> 110
王二 ---> 139
源码分析
基于JDK1.8。
不重要的方法已经清除,保留的方法已经注释。
ArrayList
package java.util;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import sun.misc.SharedSecrets;
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/** * 默认容量 */
private static final int DEFAULT_CAPACITY = 10;
/** * 空数组,用作初始化 */
private static final Object[] EMPTY_ELEMENTDATA = { };
/** * 共享空数组 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = { };
/** * 存放数据数 */
transient Object[] elementData; // non-private to simplify nested class access
/** * 数组大小,elementData存储元素数量同步 */
private int size;
/** * 构造器 */
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else { // inittialCapatity < 0 抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/** * 构造器 */
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/** * 构造器 */
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray(); // c!= null
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
// 不是一个一个取值赋值给elementData,copyOf使用System.arrayCopy(), arrayCopy使用本地方法(JNI)效率很高
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
/** * 去掉数组(elementData)中不存数据的部分 */
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
/** * 调整List大小,可以扩容和缩容,缩容时最小容量不小于10 */
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
? 0
: DEFAULT_CAPACITY;
// 小于最小容量不调整,因此最小容量不会小于10
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
/** * 最大容量 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/** * 动态扩容方法, 容量为之前的1.5倍 oldCapacity + (oldCapacity >> 1) */
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/** * 获取list大小 */
public int size() {
return size;
}
/** * 判断list是否为空 */
public boolean isEmpty() {
return size == 0;
}
// 每次取出元素操作时都会调用此方法对Ojbect数组原型进行类型转换
E elementData(int index) {
return (E) elementData[index];
}
/** * 获取元素 */
public E get(int index) {
rangeCheck(index); // 检查是否越界
return elementData(index);
}
/** * 添加元素 */
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/** * 删除 */
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null;
return oldValue;
}
/** * 两个list做差集 */
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
/** * 批量移除 */
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
// 调用回调 (e)->{ //操作e }
action.accept(elementData[i]);
}
// 遍历过程禁止修改list!
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/** * 移除步骤: * 1. 标记移除 * 2. 修改线程 * 3. 移动元素 * 4. 清除尾部元素 */
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
// 标记元素
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
// 移动元素 例如: [1][2][3] size=2 移动后 [1][3][3]
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
// 清除尾部元素
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
// 更新size
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
}
HashMap
底层数据结构:数组链表+红黑树
默认的容量为:16(1<<4)
扩容的条件:size>=容量*加载因子
扩容大小:旧容量2倍(newCap = oldCap << 1)
树化(terrify)的条件
- 容量长度大于等于64
- 链表成都大于8
树化的过程
- 把普通节点转换为TreeNode
调用treeify进行树化
- 调整节点
- 左旋右旋
put导致死循环的原因。在JDK1.7中插入元素使用头插法,插入的时候不需要遍历哈希桶,在多线程下这样可能形成循环链表。JDK8采用尾插法,循环找到最后一个节点,然后在最后一个节点插入元素。
存储结构
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
/** * 默认容量16 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/** * 最大容量,1 << 30 = 1073741824 */
static final int MAXIMUM_CAPACITY = 1 << 30;
/** * 默认加载因子,是决定存储容量扩容的关键指标,计算公式: size/总容量 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/** * 小于这个值无法使用红黑树,HashMap容量不推荐为奇数,比这个数小后树退化为数组 * 红黑树扩展时也参考这个属性 */
static final int TREEIFY_THRESHOLD = 8;
/** * 容量小于这个值红黑树将退化为数组存储 */
static final int UNTREEIFY_THRESHOLD = 6;
/** * 将数组转化为红黑树推荐的容量 */
static final int MIN_TREEIFY_CAPACITY = 64;
/** * 使用数组存储的数据结构,node节点 */
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V 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;
}
}
/** * 计算对象的hash值,是hash code分配更均匀,减少冲突几率 */
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/** * 计算2的幂次方表容量 * 也就是说表容量只能为: ... 4 8 16 32 64 128 256 ... 1024 ... 1073741824 */
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/* ---------------- Fields -------------- */
/** * 数组存储结构,默认第一次使用时会分配空间 */
transient Node<K,V>[] table;
/** * 键值对数量 */
transient int size;
/** * 对table修改的次数,调整table时改变 —— rehash、remove、add等操作 * 用来判断在读取操作过程中是否出现table修改 */
transient int modCount;
/** * 扩容时的临界值,计算为 capacity*loadFactor */
int threshold;
/** * 加载因子, 默认0.75 */
final float loadFactor;
/* ---------------- Public operations -------------- */
/** * 默认构造函数,table容量为16 */
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // 0.75
}
/** * 获取存储键值对数量 */
public int size() {
return size;
}
/** * 判空 */
public boolean isEmpty() {
return size == 0;
}
/** * 通过key获取value * 下面的getNode是核心方法。 */
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/** * 获取操作 */
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n; // n table长度
K k;
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
// 根据存储结构来获取数据
// 红黑树,调用getTreeNode
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 遍历链表
do {
//较key查询value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
/** * 添加数据 */
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/** * Implements Map.put and related methods. * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table未初始化会执行
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 存放值
if ((p = tab[i = (n - 1) & hash]) == null)// 判断通过hash计算出的位置是否有值
// 没有就在该位置(i)创建一个node并赋值
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))))
// 判断hash值、key相同,认为
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 遍历哈希桶
for (int binCount = 0; ; ++binCount) {
// 遍历到桶最后一个元素(链表最后一个元素)
if ((e = p.next) == null) {
// 添加元素
p.next = newNode(hash, key, value, null);
// 判断,只有哈希桶至少为8个的时候才进行树化,TREEIFY_THRESHOLD默认为8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 判断键值是否相同
if (e.hash == hash &&
((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;
// 超出HashMap存放元素的阈值threshold = capacity * loadFactor(0.75)
if (++size > threshold)
// 调整Hash存在空间大小
resize();
afterNodeInsertion(evict);
return null;
}
/** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */
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用来保证HashMap阈值threshold不超限
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;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 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;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
/** * 树化方法 * Replaces all linked nodes in bin at index for given hash unless * table is too small, in which case resizes instead. */
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
/* ------------------------------------------------------------ */
// Tree bins
/** * 红黑树 * * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
}
}
(完)
文章同步我的个人博客:https://www.elltor.com/archives/106.html
还没有评论,来说两句吧...