天天看点

Java集合框架源码分析集合框架

集合框架

Collection(单列)

结构图:

Java集合框架源码分析集合框架

分析:Collection接口继承了Iterator,而List又继承了Collection,因此实现List的类都具有Iterator和Collection的相关方法。

List

特点:有序,可重复

ArrayList

底层:是一个数组

分析源码

字段
//默认的初始化容量
 	private static final int DEFAULT_CAPACITY = 10;
	//空数组
	private static final Object[] EMPTY_ELEMENTDATA = {};
	//空数组
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
	//arraylist底层维护的数组
    transient Object[] 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 {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }


 public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//默认给定一个空数组
    }


//传入一个Collection接口的实现类对象
public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
           
add方法

1.无参构造器

第一次扩容

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 1; i <= 10 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//初始化数组,给定一个空数组
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

//先进行装箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//执行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量为数组大小加1,即为1
        elementData[size++] = e;
        return true;
    }

//确认数组容量
private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

//计算容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//若为空数组
            return Math.max(DEFAULT_CAPACITY, minCapacity);//则容量设为10
        }
        return minCapacity;
    }

//确认最后的容量(Explicit 明确的)
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//一个计数器,用于并发情况下的

   
        if (minCapacity - elementData.length > 0)//如果最小容量大于此时数组长度,则说明要扩容
            grow(minCapacity);//进行扩容
    }

//扩容操作
private void grow(int minCapacity) {
        int oldCapacity = elementData.length;//得到旧的数组容量(刚开始为0)
        int newCapacity = oldCapacity + (oldCapacity >> 1);//容量进行右移一位再加上原来的容量,即容量变为原来的1.5倍,即还是0
        if (newCapacity - minCapacity < 0)//如果新容量小于最小容量
            newCapacity = minCapacity;//则将最小容量赋给新容量
        if (newCapacity - MAX_ARRAY_SIZE > 0)//若新容量大于数组最大长度 (MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);//进行数组复制操作
    }

//最大容量
private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) //若最小容量认为0,则抛出异常
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;//最小容量大于最大数组长度,则返回Integer.MAX_VALUE,否则返回MAX_ARRAY_SIZE
    }


public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素赋值给数组
        return true;
    }

           

第二次扩容

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 1; i <= 10 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//先进行装箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//执行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量为数组大小加1,此时为11
        elementData[size++] = e;
        return true;
    }

//确认容量
 private void ensureCapacityInternal(int minCapacity) {
        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;//此时直接返回11
    }

//确认最后的容量
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//最小容量为11大于数组长度10,因此要进行扩容
            grow(minCapacity);
    }

//扩容操作
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//得到原来的数组长度为10
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量为旧容量乘以1.5倍之后,为15
        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);//进行数组复制操作
    }

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素赋值给数组
        return true;
    }

           

2.有参构造器

初始化容量

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(8);//初始化容量为8
        for (int i = 1; i <= 8 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {//若容量大于0
            this.elementData = new Object[initialCapacity];//进行初始化容量,即创建一个数组
        } else if (initialCapacity == 0) {//若等于0
            this.elementData = EMPTY_ELEMENTDATA;//则赋给一个数组
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }


public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(8);//初始化容量为8
        for (int i = 1; i <= 8 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//先进行装箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//执行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量为数组大小加1,即为1
        elementData[size++] = e;
        return true;
    }

//确认数组容量
private void ensureCapacityInternal(int minCapacity) {
        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;//直接返回1
    }

//确认最后的容量(Explicit 明确的)
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//一个计数器,用于并发情况下的

   
        if (minCapacity - elementData.length > 0)//如果最小容量大于此时数组长度,则说明要扩容
            grow(minCapacity);//此时并不进行扩容
    }


public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素赋值给数组
        return true;
    }
           

进行扩容

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(8);
        for (int i = 1; i <= 8 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//先进行装箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//执行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量为数组大小加1,即为9
        elementData[size++] = e;
        return true;
    }

//确认数组容量
private void ensureCapacityInternal(int minCapacity) {
        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;//直接返回9
    }

//确认最后的容量(Explicit 明确的)
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//一个计数器,用于并发情况下的

   
        if (minCapacity - elementData.length > 0)//如果最小容量(9)大于此时数组长度(8),则说明要扩容
            grow(minCapacity);//此时并不进行扩容
    }

//扩容
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//旧容量为原数组大小8
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量为8*1.5=12
        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);//进行数组复制
    }

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素赋值给数组
        return true;
    }
           

LinkedList()

底层:是一个双向链表

分析源码

字段
//链表大小
	transient int size = 0;//trasient 短暂的 序列化过程中不会被序列化
	//头结点
    transient Node<E> first;

  	//尾结点
    transient Node<E> last;
           
构造器
public LinkedList() {
    }


    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
           
add方法
public class LinkedList_ {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        for (int i = 1; i <= 10; i++) {
            list.add(i);
        }

    }
}

//无参构造器
public LinkedList() {
    }

//装箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//add方法
public boolean add(E e) {
        linkLast(e);//向链表后面追加一个元素
        return true;
    }

//链表尾部添加元素
void linkLast(E e) {
        final Node<E> l = last;//尾结点指向结点l,此时为null
        final Node<E> newNode = new Node<>(l, e, null);//创建一个新的结点,并且前驱指向l
        last = newNode;//新的结点也指向last即为null
        if (l == null)//如果结点l为null
            first = newNode;//则新节点指向头结点
        else//如果不为null
            l.next = newNode;//新节点赋给结点l的后继
        size++;//链表长度加1
        modCount++;//修改次数加1
    }



           
remove方法
public class LinkedList_ {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        for (int i = 1; i <= 10; i++) {
            list.add(i);
        }

        list.remove();
    }
}

//remove方法,其实调用的是removefirst方法
public E remove() {
        return removeFirst();
    }

//removeFirst方法
public E removeFirst() {
        final Node<E> f = first;//将头结点赋值给一个结点
        if (f == null)//如果头结点为null,则抛出异常
            throw new NoSuchElementException();
        return unlinkFirst(f);//进入unlinkFirst方法
    }

//unlinkFirst方法
private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;//取出头结点中的值
        final Node<E> next = f.next;//将头结点的下一个元素赋给一个结点
        f.item = null;//将头结点的值赋为null
        f.next = null; //null赋给头结点的后继指向,利用GC将其回收( help GC)
        first = next;//将头结点的后继结点赋给头结点
        if (next == null)//若后继节点为null
            last = null;//则null赋给尾结点
        else
            next.prev = null;//否则将null赋给后继节点的前驱指向
        size--;//链表大小减1
        modCount++;//修改次数+1
        return element;//返回值
    }
           

ArrayList和LinkedList的对比

  • 增删用LinkedList,查找用ArrayList。

Vector

分析源码

字段
//数组
	protected Object[] elementData;

	//数组中元素个数
    protected int elementCount;

    //容量每次增加的值
    protected int capacityIncrement;
	
	//数组的最大大小
	private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
           
构造器
//有参构造器(初始化容量,容量增长量)
	public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

   //有参构造器(初始化容量)
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    //无参构造器
    public Vector() {
        this(10);
    }

    //可以传入一个Collection的实现类对象
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }
           
add方法

1.无参构造

public class Vector_ {
    public static void main(String[] args) {
        Vector vector = new Vector();
        for (int i = 1; i <= 10 ; i++) {
            vector.add(i);
        }
        vector.add(100);//达到10个之后,进行扩容
    }
}

//进入无参构造器
public Vector() {
        this(10);//初始化容量默认为10
    }

public Vector(int initialCapacity) {
        this(initialCapacity, 0);//容量增加量默认为0
    }

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];//在这里生成一个数组赋给elementData
    this.capacityIncrement = capacityIncrement;//容量增长量为0
}

//装箱
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//add操作,与ArrayList不同的是加上了synchronized关键字(因此,vector是线程安全的)
 public synchronized boolean add(E e) {
        modCount++;//修改次数加1
        ensureCapacityHelper(elementCount + 1);//需要容量为当前数组个数+1,即0+1=1
        elementData[elementCount++] = e;
        return true;
    }

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code()
        if (minCapacity - elementData.length > 0)//如果最小容量(0)大于数组的大小(10),因此并不需要扩容
            grow(minCapacity);//进行扩容
    }


//第二次扩容  vector.add(100);//达到10个之后,进行扩容

 public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//此时11>10,因此要进行扩容
            grow(minCapacity);
    }

//扩容
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//记录旧容量
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);//若容量增量大于0,则新容量等于旧容量+容量增量;否则,加上旧容量,即为2倍,此时为20
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);//进行数组复制
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;//将元素复制给数组
        return true;
    }

           

2.指定初始化容量

public class Vector_ {
    public static void main(String[] args) {
        Vector vector = new Vector(8);
        for (int i = 1; i <= 8 ; i++) {
            vector.add(i);
        }
        vector.add(100);
    }
}

public Vector(int initialCapacity) {
        this(initialCapacity, 0);//此时初始容量为8
    }

public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];//赋一个数组大小为8的数组
        this.capacityIncrement = capacityIncrement;
    }



//add操作相同

//进行扩容操作 vector.add(100);

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);//此时所需最小容量为9,
        elementData[elementCount++] = e;
        return true;
    }

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//9>8
            grow(minCapacity);//因此要进行扩容
    }

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//记录旧容量为10
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);//新容量为10*2=20
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);//复制元素
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;//将元素赋值给数组
        return true;
    }

           

ArrayList与Vector对比

  • ArrayList是线程不安全的,而Vector是线程安全的
  • ArrayList比Vector效率更高

Set

特点:无序,不能重复

结构

Java集合框架源码分析集合框架

HashSet

分析源码

字段
//维护的map
	private transient HashMap<E,Object> map;
	//值
    private static final Object PRESENT = new Object();
           
构造器
//无参构造器
	public HashSet() {
        map = new HashMap<>();
    }

 	//可以传入一个Collection的实现类
    public HashSet(Collection<? extends E> c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

	//有参构造器(初始化容量,加载因子)
    public HashSet(int initialCapacity, float loadFactor) {
        map = new HashMap<>(initialCapacity, loadFactor);
    }
	
	//有参构造器(初始化容量)
    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }

	//底层可以使用LinkedHashMap
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }
           
add方法
public class HashSet_ {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        for (int i = 1; i <= 12 ; i++) {
            hashSet.add(i);
        }
        hashSet.add(200);
    }
}

//HashSet的底层其实就是HashMap
 public HashSet() {
        map = new HashMap<>();
    }

//初始化HashMap
 public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // 加载因子默认为0.75
    }

//装箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//add方法其实就是调用HashMap的put方法
public boolean add(E e) {
        return map.put(e, PRESENT)==null;//传入键e,值是 static final Object PRESENT = new Object();
    }

//put操作
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);//首先计算Key的hash值
    }

//hash操作
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//一个对hash值操作的算法
    }


//putVal操作
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)//如果hash表为空
            n = (tab = resize()).length;//则进行初始化,并得到hash表的长度
        if ((p = tab[i = (n - 1) & hash]) == null)//将长度与hash值进行运算得到该元素在hash表中的索引,若此索引处没有元素
            tab[i] = newNode(hash, key, value, null);//直接new一个新的结点在此位置上
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//比较数组中的元素与即将放入的元素的hash并且比较key值和equals结果,若相等则不放入,将该元素赋给e
                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) {//若后继节点为null
                        p.next = newNode(hash, key, value, null);//则直接在后面添加一个结点
                        if (binCount >= TREEIFY_THRESHOLD - 1) //若链表元素的个数大于 static final int TREEIFY_THRESHOLD = 8;
                            treeifyBin(tab, hash);//则进行树化
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))//进行比较该元素和即将放入元素的hash值和key值
                        break;
                    p = e;//将e指向p,一个接一个遍历
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//修改次数+1
        if (++size > threshold)//当hash表的长度大于阈值(12)时,会进行扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }


//resize操作(扩容)
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//计算出原来的hash表的长度
        int oldThr = threshold;//得到旧阈值
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {//若旧容量大于static final int MAXIMUM_CAPACITY = 1 << 30
                threshold = Integer.MAX_VALUE;//则阈值设置成最大正型
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)//在这里新的容量赋为原来的2倍
                newThr = oldThr << 1; // 新的阈值设置成原来的2倍
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;//新容量默认为16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//新阈值为加载因子*默认容量=0.75*16=12
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;//将新阈值赋给map的阈值
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//初始化一个Node节点的数组,大小为新容量,即为16
        table = newTab;//并将这个新hash表赋给map中的hash表
        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;
    }

//treeifyBin操作
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)//若hash表的长度小于最小树化大小(64),则不会进行树化,而是进行hash表的扩容
            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);
        }
    }
           

LinkedHashSet

特点:LinkedHashSet是有序的,其实它就是数组加双向链表,每次加入一个结点,就加入道双向链表中

字段

构造方法
public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    public LinkedHashSet() {
        super(16, .75f, true);
    }

    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
           
add方法
public class LinkedHashSet_ {
    public static void main(String[] args) {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        for (int i = 1; i <= 10; i++) {
            linkedHashSet.add(i);
        }
    }
}

public LinkedHashSet() {
        super(16, .75f, true);//初始化容量为16,加载因子为0.75
    }

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);//LinkedHashSet底层其实就是LinkedHashMap
    }

public LinkedHashMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
        accessOrder = false;
    }

 public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;//进行初始化参数
        this.threshold = tableSizeFor(initialCapacity);
    }


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;
            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);
                        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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//在这里将其结点指向
        return null;
    }
           

TreeSet

特点:

  • 其底层是TreeMap
  • 有序
  • 当hash表存入一个结点的同时,会有EntrySet里面存放指向这个结点的指针,用于快速遍历map

分析源码

字段
private transient NavigableMap<E,Object> m;

    private static final Object PRESENT = new Object();
           
构造器
TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

    public TreeSet() {
        this(new TreeMap<E,Object>());
    }

    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }
           
add操作
public class TreeSet_ {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet(new Comparator() {//若没有构造器,会采用自己的系统默认的构造器
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });
        treeSet.add("mike");
        treeSet.add("jack");
        treeSet.add("lucy");
        System.out.println("treeSet="+treeSet);
    }
}

public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

 public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

 public boolean add(E e) {
        return m.put(e, PRESENT)==null;//值默认为object
    }

public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {//利用自己的构造器的compare进行比较
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }
           

Map(双列)

结构图:

Java集合框架源码分析集合框架

HashMap

分析源码

字段
//hash表初始化的大小为16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //hash表的最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默认的加载因子为0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //链表转红黑树的结点数为8
    static final int TREEIFY_THRESHOLD = 8;

    //红黑树转链表的结点数为6(剪枝)
    static final int UNTREEIFY_THRESHOLD = 6;

    //最小的树化hash表大小为64
    static final int MIN_TREEIFY_CAPACITY = 64;
           
构造器
public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
           
put操作
public class HashMap_ {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put("java",10);
        hashMap.put("php", 10);
        hashMap.put("java", 20);
    }
}

public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

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;
            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);
                        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) { //当链表中存在这个相同的结点时
                V oldValue = e.value;//记录这个结点的值
                if (!onlyIfAbsent || oldValue == null)//如果旧value为null的话
                    e.value = value;//将这个即将加入的结点的value赋给此节点的value
                afterNodeAccess(e);
                return oldValue;//返回老结点的value,即当put进去同一个key的键值对的话,做替换工作,返回旧的value
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
           

HashTable

特点:hashtable是线程安全的,并且key和value不能为null

分析源码

字段
private transient Entry<?,?>[] table;

    private transient int count;

    private int threshold;

    private float loadFactor;

    private transient int modCount = 0;
           
构造器
public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

    public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

    public Hashtable() {
        this(11, 0.75f);
    }

    public Hashtable(Map<? extends K, ? extends V> t) {
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }
           
put操作
public class HashTable_ {
    public static void main(String[] args) {
        Hashtable hashtable = new Hashtable();
        for (int i = 1; i <= 12 ; i++) {
            hashtable.put(i, i);
        }
    }
}

public Hashtable() {
        this(11, 0.75f);//初始化容量为11,加载因子为0.75
    }

public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//put操作,由于加上了synchronized关键字,因此hashtable是线程安全的
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {//若value为null,则会抛出空指针异常
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry<?,?> tab[] = table;
        if (count >= threshold) {//阈值为11*0.75=8
            // Rehash the table if the threshold is exceeded
            rehash();//在这里会进行hash扩容

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }


protected void rehash() {
        int oldCapacity = table.length;
        Entry<?,?>[] oldMap = table;

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;//新容量为旧容量*2+1
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;

        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }
           

Properties

特点:其底层是hashtable

字段
构造方法
public Properties() {
        this(null);
    }

    public Properties(Properties defaults) {
        this.defaults = defaults;
    }
           
put方法
public class Properties_ {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("jack", "杰克");
        properties.put("mike", "迈克");
        System.out.println(properties);
    }
}

public Properties() {
        this(null);
    }

 public Properties(Properties defaults) {
        this.defaults = defaults;
    }

 public Hashtable() {
        this(11, 0.75f);
    }


//下面与hashtable相同
           

TreeMap

特点:有序

分析源码

字段
private final Comparator<? super K> comparator;

    private transient Entry<K,V> root;

    private transient int size = 0;

    private transient int modCount = 0;
           
构造器
//初始化
	public TreeMap() {
        comparator = null;//compartor会设置为null
    }

	//有参构造(传入一个comparator的实现类)
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }

    public TreeMap(SortedMap<K, ? extends V> m) {
        comparator = m.comparator();
        try {
            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }
    }
           
put操作
public class TreeMap_ {
    public static void main(String[] args) {
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });
        treeMap.put("jack", "杰克");
        treeMap.put("mike", "迈克");
        treeMap.put("lucy", "露西");
        System.out.println("treeMap"+treeMap);

    }
}

public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;//在这里获取构造器中的comparator
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);//利用比较器里面的compare方法进行比较
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else//在这里,如果比较器为0,则说明相等
                    return t.setValue(value);//新的值替换掉旧的值
            } while (t != null);
        }
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }


 TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });