浅沫记忆 发表于 2021-9-18 18:45:37

ArrayList及HashMap的扩容规则讲解

今天小编就为大家分享一篇关于ArrayList及HashMap的扩容规则讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
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 intmax_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)) {
    resize(2 * table.length);
    hash = (null != key) ? hash(key) : 0;
    bucketindex = indexfor(hash, table.length);
}
createentry(hash, key, value, bucketindex);
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对CodeAE代码之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/u012099869/article/details/50411767

http://www.zzvips.com/article/176525.html
页: [1]
查看完整版本: ArrayList及HashMap的扩容规则讲解