- ArrayListlinkedListVector
Listlist = new ArrayList<>(); -----------之后的执行过程------------- public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } //其中 transient Object[] elementData; // non-private to simplify nested class access private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
调用了构造方法后让list的对象中的elementData属性等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA
即elementData为一个空的Object类型的数组,对其进行了初始化,此时list.size()的返回为0,因为对象中的size属性还没变化
list.add(5);
-----------之后的执行过程-------------
//先进行自动装箱valueOf
//然后调用了ArrayList中的add方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!,此时size仍旧为0,执行完grow方法后返回
elementData[size++] = e; // 让elementData[0] = e;再返回
return true;
}
private void ensureCapacityInternal(int minCapacity) { // minCapacity为1
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); // calculateCapacity()的返回值为10
}
private void ensureExplicitCapacity(int minCapacity) { // 传入的参数为10
modCount++; //修改次数 + 1
// overflow-conscious code
if (minCapacity - elementData.length > 0) //10 - 0 > 0,条件成立
grow(minCapacity);
}
private void grow(int minCapacity) { // 传入的参数为10
// overflow-conscious code
int oldCapacity = elementData.length; // 0
int newCapacity = oldCapacity + (oldCapacity >> 1); // 0
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity; // 10
if (newCapacity - MAX_ARRAY_SIZE > 0) // MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity); // 从原来的elementData中copy新的长度返回给elementData
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //这个条件成立
return Math.max(DEFAULT_CAPACITY, minCapacity);//DEFAULT_CAPACITY = 10;
}
return minCapacity;
}
在第一个容量增长为10以后,只要list长度不超过10,那么就不会再执行增长容量,否则以1.5倍的速度增长,即下面代码发挥了作用
int newCapacity = oldCapacity + (oldCapacity >> 1); -----------分界线------------- Listlist = new ArrayList<>(5); System.out.println(list.size()); // 此时输出仍为0,而elementData.length=5
之后的过程中只要往list中加入第6个元素,那么就会触发grow方法,按照5*1.5进行增长~~
结论:ArrayList本质上是数组,其中的方法本质上就是在对数组进行操作
分析linkedListListlist = new linkedList<>(); // transient int size = 0; -----------之后的执行过程------------- //之后就是调用了一个无参构造方法,什么也没做 list.add(5); -----------之后的执行过程------------- public boolean add(E e) { linkLast(e); return true; } //调用了linkLast方法 void linkLast(E e) { final Node l = last; // transient Node last; final Node newNode = new Node<>(l, e, null); // 新节点的前一个是last,后一个为空,Node是一个双向链表 last = newNode; // 把last指向newNode if (l == null) //第一次添加节点的时候l为空~~ first = newNode; // transient Node first; // 让first指向这个第一个添加的节点 else l.next = newNode; // 让上一个节点的next指向newNode size++; modCount++; } //注意以下的都是linkedList的方法,不是List接口中的方法 //getFirst,getLast,removeFirst,removeLast,addFirst,addLast public E remove() { return removeFirst(); }// remove的无参方法是移除最后一个 public void push(E e) { addFirst(e); } public E pop() { return removeFirst(); }
结论:没有扩容机制,而且可以得出linkedList具有能够实现栈的所有功能的方法,因此可以直接将linkedList作为栈使用,但注意不能向上转型用List接收
分析Vector(线程安全!!synchronized底层仍然是数组
Listlist = new Vector<>(); -----------之后的执行过程------------- 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]; // protected Object[] elementData;空的Object数组 this.capacityIncrement = capacityIncrement; } //因此我们得出在初始化得到一个Vector对象时默认大小是10,可以设置增长的容量大小,默认为0 list.add(5); public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); // elementCount默认为0 elementData[elementCount++] = e; return true; } private void ensureCapacityHelper(int minCapacity) { // overflow-conscious code if (minCapacity - elementData.length > 0) // 只要其中的元素个数不超过初始大小10就不会扩容,添加第11个时扩容 grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; 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); }
结论:Vector与ArrayList一样底层都是数组,只不过Vector的扩容机制与其不同,而且Vector是线程安全的
经对比发现,ArrayList与Vector没什么不同,只是扩容机制上的区别以及线程安全的区别,而linkedList本质上是双向链表,可当作栈来使用,没有扩容机制…在使用这三个类时都可以用List接口的get与add方法,都是有序的
- HashSetlinkedHashSetTreeSet
Setset = new HashSet<>(); -----------之后的执行过程------------- public HashSet() { map = new HashMap<>(); } //可以看到HashSet对象里的属性用的时hashMap对象 public HashMap() { // final float loadFactor; 加载因子默认为0.75 this.loadFactor = DEFAULT_LOAD_FACTOR; //DEFAULT_LOAD_FACTOR = 0.75f; } set.add("Jack"); -----------之后的执行过程------------- public boolean add(E e) { // PRESENT为HashSet的类属性 return map.put(e, PRESENT)==null; // Object PRESENT = new Object(); } // map.put()返回的是值对应的类型,即Object类型 public V put(K key, V value) { // 调用HashMap中的put方法 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); // hashCode是key所属类型的hashCode方法 } // 1. 先计算key的hash值,HashMap中hash值的计算与hashCode值不相同,右移16位后作异或操作 // 2. 进入HashMap中的putVal方法中 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node [] tab; Node p; int n, i; // 首先定义了会用到的变量 if ((tab = table) == null || (n = tab.length) == 0) // transient Node [] table;一个节点数组 n = (tab = resize()).length; // 第一次执行完n为16 if ((p = tab[i = (n - 1) & hash]) == null) // 根据n-1与hash值相与计算出存放的下标并判断此处是否为空 tab[i] = newNode(hash, key, value, null); // 为空,则直接赋值 else { Node 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 )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; } //第一次加入元素时执行resize中的 newCap = DEFAULT_INITIAL_CAPACITY; // 初始值为16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 门槛为12 //并将 Node [] newTab = (Node [])new Node[newCap]; table = newTab; // 即第一次table的大小为16 根据hash值以及table的size计算出i的位置然后判断此处是否有元素,没有元素则加入,然后退出 ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null;
resize方法
final Node[] resize() { Node [] 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 [] newTab = (Node [])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node 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 )e).split(this, newTab, j, oldCap); else { // preserve order Node loHead = null, loTail = null; Node hiHead = null, hiTail = null; Node 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; }
第二次加入元素仍然执行上述的添加过程,不用再resize();
set.add("Tom");
set.add("Mary");
set.add("Mary");
-----------添加第二个Mary之后的执行过程-------------
//此时当执行为false
if ((p = tab[i = (n - 1) & hash]) == null)
//那么进入
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//判断已存在i这个位置的元素的hash值是否与当前加入的元素的hash值相同?并且key相同(同一个对象)或者用equals比较后相同
e = p;
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
//会替换原来的旧值,并返回旧值
而如果是加入的对象,那么此时set集合中有两个dog对象
set.add(new Dog("Jack", 1));
set.add(new Dog("Jack", 1));
如果重写了Dog类中的equals和hash方法,再想要加入这两个对象时,就只能加入一个,因为hash值相同,并且equals判断也相等
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dog dog = (Dog) o;
return age == dog.age && Objects.equals(name, dog.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
第一种扩容机制,当加入第13个元素的时候会触发,那么table扩大一倍,threshold扩大一倍
if (++size > threshold)
resize();
第二种扩容机制,当table数组的某个i的位置达到了长度为8时。再往后添加一个元素后会触发扩容机制,table容量变为32,threshold变为24,再往后添加一个元素时会使table容量变为64,threshold变为48,而再添加元素时,这个i位置的链表会变成红黑树,即同一条链表上添加了11个元素以后会进行树化,转成红黑树
在Dog类中增加了以下方法使其挂在一条链表上,去掉了重写的equals方法
@Override
public int hashCode() {
return 100;
}
结论:最终得出HashSet即等同于HashMap



