感受
说白了要不是面试的时候可能需要我压根懒得看源码,绕过来绕过去看着头疼。后面也是忍辱负重咬着呀坚持了几天,有了一种说不上来的感觉感觉有一丝丝美妙。想想还是坚持把源码看懂得了,至少跟朋友面试官聊起来有点儿装逼的资本。可能某些地方不对,欢迎大家帮我纠正,我是小白!
目录
ArrayList
ArrayList list = new ArrayList<>();
//数组默认初始值
transient Object[] elementData;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//无参构造方法
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//结论
ArrayList无参构造方法时使用懒加载模式
//初始化传入参数
ArrayList list = new ArrayList<>(5);
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//通过传入的参数指定数组大小
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
add
//数组追加值
list.add(1);
//初始参数
//元素个数
private int size;
//数组大小
transient Object[] elementData;
//数组不指定大小初始化赋值
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//第一次扩容值
private static final int DEFAULT_CAPACITY = 10;
public boolean add(E e) {
//第一次 0+1
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//elementData数组初始值 minCapacity元素个数
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//无参构造方法时 elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//DEFAULT_CAPACITY初始值==10 minCapacity元素个数 两者比较取最大的值
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
//指定数组长度时
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// minCapacity上一步返回的值-数组长度
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//oldCapacity >> 1 ==10/2=5
int newCapacity = oldCapacity + (oldCapacity >> 1);
//newCapacity==数组长度+数组长度/2
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 生成一个新的数组 长度newCapacity 简称:扩容原来的1.5倍
elementData = Arrays.copyOf(elementData, newCapacity);
}
get
//获取下标值
list.get(0);
public E get(int index) {
rangeCheck(index);
//根据下标获取值
return elementData(index);
}
private void rangeCheck(int index) {
//size数组长度
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
remove
//根据下标删除
list.remove(1);
public E remove(int index) {
//判断索引是否越界
rangeCheck(index);
modCount++;
//先获取指定下标值
E oldValue = elementData(index);
//计算删除下标后面的长度
int numMoved = size - index - 1;
if (numMoved > 0)
//比如删除index==3 拿到index后面的数据整体往前移动
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
Vector
Vector vector = new Vector<>();
//Vector 默认初始长度10 与ArrayList区别 ArrayList懒加载
public Vector() {
this(10);
}
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
add
//添加数据
vector.add(1);
//初始值
protected int elementCount;
protected Object[] elementData;
protected int capacityIncrement;
//线程安全synchronized同步锁
public synchronized boolean add(E e) {
modCount++;
//elementCount每次加一
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
//判断当前元素个是否大于数组长度
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//数组长度+ capacityIncrement==初始化的时候指定的扩容值 如果没指定就+数组长度
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//拷贝原来的数据生成新的数组
elementData = Arrays.copyOf(elementData, newCapacity);
}
get
//根据下标查询
vector.get(0);
synchronized
public synchronized E get(int index) {
//判断下标是否越界
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
//根据下标取值
return elementData(index);
}
remove
//根据下标删除
vector.remove(0);
synchronized
public synchronized E remove(int index) {
modCount++;
//判断下标越界
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
//获取当前下标值
E oldValue = elementData(index);
//计算要删除下标后面数据的长度
int numMoved = elementCount - index - 1;
if (numMoved > 0)
//删除下标数据前面的数组+后面的数据整体往前面移动
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--elementCount] = null; // Let gc do its work
return oldValue;
}
LinkedList
//链表 双向链表
LinkedList linkedList = new LinkedList<>();
//最前面的数据
transient Node<E> first;
//最后的数据
transient Node<E> last;
add
//添加数据
linkedList.add(1);
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
//最后一个节点赋值给l
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
//最后一个节点赋值为当前节点
last = newNode;
if (l == null)
//当l为null说明第一次添加数组,首节点==当前节点
first = newNode;
else
//非第一次添加数据 上一个.next指向当前节点
l.next = newNode;
size++;
modCount++;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
//item==传入的值
this.item = element;
//当前节点下一个元素为null
this.next = next;
//当前节点上一个元素为上次的尾节点
this.prev = prev;
}
}
get
//获取元素
linkedList.get(0);
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
private void checkElementIndex(int index) {
//判断下标是否越界
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
Node<E> node(int index) {
//通过穿如的下标折中 size >> 1==size/2
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
remove
//根据下标删除
linkedList.remove(0);
public E remove(int index) {
//判断下标是否越界
checkElementIndex(index);
return unlink(node(index));
}
//折中找到传入下标的节点
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
E unlink(Node<E> x) {
// 当前元素
final E element = x.item;
//下一个节点
final Node<E> next = x.next;
//上一个节点
final Node<E> prev = x.prev;
//上一个元素为null说明当前元素为首节点
if (prev == null) {
//节点赋值为下一个节点
first = next;
} else {
//不是首节点 当前节点的上一个节点指向下一个节点
prev.next = next;
//当前节点上一个节点赋值为null
x.prev = null;
}
//当前元素的下一个节点为null 说明当前节点是尾节点
if (next == null) {
当前节点的上一个节点赋值给尾节点
last = prev;
} else {
//
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
HashSet
HashSet hashSet = new HashSet<>();
//初始化底层调用hashmap
map = new HashMap<>();
add
//hashset添加元素
hashSet.add(1);
//元素初始化
private static final Object PRESENT = new Object();
public boolean add(E e) {
//底层调用hashmap put操作
return map.put(e, PRESENT)==null;
}
remove
//hashset删除元素
vector.remove(0);
//底层调用hashmap删除操作
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
HashMap
HashMap hashMap = new HashMap<>();
//默认初始值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
final float loadFactor;
//HashMap无参构造方法默认初始化
public HashMap() {
//给加载因子赋值
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
put
//HashMap put元素
hashMap.put(1, 1);
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
//判断传入的key是否为null
//要是不为null 拿到key的hashcode (h >>> 16)右移动16位,高位补零 (h ^ (h >>> 16)) 异或 (^) 操作符结合原始哈希码 h 和右移后的哈希码 总结:降低hash冲突
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//初始值
transient Node<K,V>[] table;
static final int TREEIFY_THRESHOLD = 8;
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//当前数组长度赋值给tab判断是否为null || 数组长度是否为0
if ((tab = table) == null || (n = tab.length) == 0)
//符合条件是 调用resize扩容方法
n = (tab = resize()).length;
//判断计算出来的下标位值是否有值 (n - 1) & hash降低hash冲突
if ((p = tab[i = (n - 1) & hash]) == null)
//当前下标位值为null时 直接存
tab[i] = newNode(hash, key, value, null);
else {
//当前下标位值有值的情况下
Node<K,V> e; K k;
//hash比较 && eques比较判断是否重复存入
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断是否红黑树
else if (p instanceof TreeNode)
//节点数量低于6个时红黑树推化链表
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
// p.next==null 说明当前节点是尾节点
if ((e = p.next) == null) {
//尾节点指向新节点
p.next = newNode(hash, key, value, null);
//链表长度大于等于8 切数组长度大于64 转换红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//循环比较key是否相同
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;
//size统计当大于阈值的时候扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//初始值
transient Node<K,V>[] table;
int threshold;
//hashmap的最大容量 每左移一位相当于乘以2。 1<<30=1073741824
static final int MAXIMUM_CAPACITY = 1 << 30;
//初始容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//扩容方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//判断数组长度是否>0
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
//integer的最大值赋值threshold 阈值
threshold = Integer.MAX_VALUE;
return oldTab;
}
//判断数组长度x2是否小于最大容量 && 数组长度是否大于16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//长度x2
newThr = oldThr << 1; // double threshold
}
//判断阈值是否大于0
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//newCap==16 第一次调用put操作数组长度为16
newCap = DEFAULT_INITIAL_CAPACITY;
//newThr==12 第一次调用put操作阈值为12
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);
}
//拿到newThr赋值给阈值
threshold = newThr;
//newCap 新的newTabl长度
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//判断原来数组是否为null 不为null进行迁移数据到扩容后的数组中
if (oldTab != null) {
//循环遍历原数组
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//把遍历的当前数据赋值给e 判断是否为null
if ((e = oldTab[j]) != null) {
//把原数组当前数据赋值为null
oldTab[j] = null;
//判断e下一个节点是否为null
if (e.next == null)
//拿到原来数组当前数据的hashcodo 位于运算 扩容后长度-1计算出扩容后存放位置
newTab[e.hash & (newCap - 1)] = e;
//判断是否是红黑树
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // e.next!=null 又不是红黑树 说明是链表
//低位链表
Node<K,V> loHead = null, loTail = null;
//高位链表
Node<K,V> hiHead = null, hiTail = null;
//遍历的下一个节点
Node<K,V> next;
do {
//遍历的当前节点的下一个节点赋值操作
next = e.next;
//位于运算拿到一个新的值e.hash & oldCap==0/1
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;
}
//遍历的节点下一个节点为null 说明是尾节点
} 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;
}
//可以看出hashmap底层用的单项链表
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
get
hashMap.get("1");
public V get(Object key) {
Node<K,V> e;
//计算hash值
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; K k;
//判断数组是否为null 长度是否>0 数组根据计算出的下标是否为null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//比较hash值和key值获取
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//.next不等于null 说明是链表或者红黑树
if ((e = first.next) != null) {
//红黑树 o(logn)
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//链表 循环比较 o(n)
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
remove
hashMap.remove(1);
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
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 &&
(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;
}
ConcurrentHashMap 正在拼命阅读中.....
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();