1、都是可扩容的容器。
HashMap具有2个关于扩容相关的字段,当容器元素达到threshold后就会进行扩容,而threshold的值与负载因子loadFactor(0.75)有关。
初始容量16,此时threshold = 16 * 0.75 = >12。 而每次扩容都是原容量的2倍。
具体扩容的步骤详见源码。
int threshold;
final float loadFactor;
而ArrayList不存在负载因子这一概念,当新增元素超出数组长度时进行扩容,而扩容后的长度为扩容前的1.5倍。
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);
}
关于HashMap的扩容里面还有很深的门道,有兴趣可以研究研究。
2、ArrayList是数组结构,而HashMap是数组+链表结构。
transient Object[] elementData;//ArrayList
transient Node<K,V>[] table;//HashMap
注意都是用transient修饰的,不参与序列化,那ArrayList和HashMap是如何序列化的?
都是使用的 writeObject()和 readObject()方法进行的。