ArrayList及HashMap的扩容规则讲解

时间:2022-03-18 22:47:36

1、arraylist

默认大小为10

?
1
2
3
4
/**
 * default initial capacity.
*/
private static final int default_capacity = 10;

最大容量为2^30 - 8

?
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * 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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * 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

?
1
2
3
4
/**
 * the default initial capacity - must be a power of two.
*/
static final int default_initial_capacity = 1 << 4; // aka 16

最大容量为:2^30

?
1
2
3
4
5
6
/**
 * 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次方整数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * 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);
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/u012099869/article/details/50411767