时间:2021-05-20
1、ArrayList
默认大小为10
/** * Default initial capacity.*/private static final int DEFAULT_CAPACITY = 10;最大容量为2^30 - 8
/** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;/** * A constant holding the maximum value an {@code int} can * have, 2<sup>31</sup>-1.*/public static final int MAX_VALUE = 0x7fffffff;扩容规则为:oldCapacity*1.5
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * @param minCapacity the desired minimum capacity */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);}2、HashMap
默认大小: 16
/** * The default initial capacity - MUST be a power of two.*/static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16最大容量为:2^30
/** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30.*/static final int MAXIMUM_CAPACITY = 1 << 30;扩容规则为:大于oldCapacity的最小的2的n次方整数
/** * Adds a new entry with the specified key, value and hash code to * the specified bucket. It is the responsibility of this * method to resize the table if appropriate. * Subclass overrides this to alter the behavior of put method. */void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex);}总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
Java容器类包含List、ArrayList、Vector及map、HashTable、HashMapArrayList和HashMap是异步的,Vector
HashMap扩容前言:HashMap的size大于等于(容量*加载因子)的时候,会触发扩容的操作,这个是个代价不小的操作。为什么要扩容呢?HashMa
注意:不同的JDK版本的扩容机制可能有差异实验环境:JDK1.8扩容机制:当向ArrayList中添加元素的时候,ArrayList如果要满足新元素的存储超过A
本文基于jdk1.8进行分析。ArrayList和HashMap是我们经常使用的集合,它们不是线程安全的。我们一般都知道HashMap的线程安全版本为Concu
复制代码代码如下:packagecom.lkb.test;importjava.util.ArrayList;importjava.util.HashMap;i