文章目录
一、ArrayList源码分析
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
for (int i = 0; i < 10; i++) {
arrayList.add(i);
}
}
1、创建对象
执行ArrayList arrayList = new ArrayList();
会进入ArrayList类的构造器
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
DEFAULTCAPACITY_EMPTY_ELEMENTDATA
是一个空的数组,初始化为空集合
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
2、add()
第一次执行 arrayList.add(i);
因为i的值为int类型,所以首先会进入以下代码将i的值进行装箱
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
回到程序这时的i为Integer类型,然后执行add方法。
3、判断当前容量大小
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
ensureCapacityInternal(size + 1);
进入该方法。
private void ensureCapacityInternal(int minCapacity) { // minCapacity为size+1
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
calculateCapacity();
该方法首先判断当前对象的数组是否为空,如果为空返回Math.max(DEFAULT_CAPACITY, minCapacity)
,如果不为空,返回参数容量。
其中DEFAULT_CAPACITY
初始为10,minCapacity
则是size+1,因为是第一次增加元素,size并没有赋值默认为0。将DEFAULT_CAPACITY
和minCapacity
进行比较,返回最大的10。
private void ensureExplicitCapacity(int minCapacity) { // 此时minCapacity为10
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
modCount
这个变量实在ArrayList
的父类AbstractList
中定义,用来记录当前对象中集合被修改的次数
4、扩容
当前对象集合容量不够时,进入grow()
方法
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length; // 0
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);
}
int newCapacity = oldCapacity + (oldCapacity >> 1);
新的容量是老的容量的1.5倍,由于第一次执行oldCapacity
为0,所以newCapacity
也为0。当执行第二次扩容时按照当前容量的1.5倍进行扩容。
然后将最小容量赋给新容量。
5、赋值
elementData = Arrays.copyOf(elementData, newCapacity);
copyOf使elementData扩容10个容量,然后将容量为10的集合赋给elementData
回到add方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e; // 此时elementData容量为10
return true;
}
elementData[size++] = e;
将e元素赋给size下标位置
二、LinkedList源码分析
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add("xiaoming");
linkedList.add("xiaoming");
linkedList.add("xiaoming");
}
1、创建对象
初始化一个空的对象,first = null,last = null;
first指向头结点,last指向尾结点。
public LinkedList() {
}
2、add()
public boolean add(E e) {
linkLast(e);
return true;
}
进入linklast()
方法
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
final Node<E> newNode = new Node<>(l, e, null);
创建一个新结点对象,这个结点e为xiaoming,prev为last,next为null。最后last指向新结点,因为是第一次添加,所以first也指向新结点。如果当前不是第一次添加,则会采用尾插法插入数据。
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
三、HashSet源码分析
HashMap存储结构图
HashSet的底层是HashMap
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("xiaoming");
hashSet.add("xiaosi");
hashSet.add("xiaoli");
hashSet.add("xiaohong");
}
1、创建对象
public HashSet() {
map = new HashMap<>();
}
调用该构造方法,创建HashMap的对象。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
DEFAULT_LOAD_FACTOR
默认值为0.75f
2、add()
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
该方法会调用map的put方法。而put方法需要两个参数,这时源码赋一个空的PRESENT作为占位符
private static final Object PRESENT = new Object();
进入map的put方法。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
返回putVal方法,其中hash(key)
会调用hashcode()
方法对key值进行算法操作,得到一个hash值,该hash值就代表当前数据存放的位置。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
3、数据存放操作
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数组是否为null,若为则进行扩容并且返回给n
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 判断当前结点是否为空,若为空则将当前数据添加到tab表中
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 若当前结点不为空时进入该操作
else {
Node<K,V> e; K k;
// 判断已经存储该下标的数据是否和当前数据相等(通过hashcode和euqals判断)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 判断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);
// 如果结点数大于7时将单链表转换成红黑树
// static final int 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;
// 如果当前table表实际容量大于临界值时则进行扩容。
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
table是当前对象的一个结点数组属性。table数组中每一个结点都是Node类型。
transient Node<K,V>[] table;
Node是一个内部类。包含以下属性。
final int hash;
final K key;
V value;
Node<K,V> next;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
4、扩容
当table为空时,也就是当前集合没有元素时,执行n = (tab = resize()).length;
。此时会进入resize方法
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);
}
....
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
}
因为table为null,所以oldCap为0 会执行以下操作。newCap是新容量,newThr为预警容量(临界值)。当newThr容量为现在容量的0.75时开始扩容。
newCap = DEFAULT_INITIAL_CAPACITY; // static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // static final float DEFAULT_LOAD_FACTOR = 0.75f;
以下代码首先会创建一个newCap容量的Node数组。然后将该结点赋给table,此时的table容量就是16。
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);