本文介绍了ArrayList 容量增量公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JDK 1.7 的 ArrayList.java 中,方法 ensureCapacity 使用以下表达式增加数组容量:int newCapacity = oldCapacity + (oldCapacity >> 1) 所以看起来新的容量几乎比旧的多 50%.

In the JDK 1.7 into the ArrayList.java the method ensureCapacity increments the array capacity using the following expression: int newCapacity = oldCapacity + (oldCapacity >> 1) so it seems that the new capacity will be almost the 50% more than the old.

但是很多书上都说容量翻倍了……所以书没更新还是我看不懂?

However in many books is said that the capacity is doubled... so the books aren't updated or I don't understand well?

推荐答案

你的理解是对的,newCapacity比oldCapacity多了50%

You're understanding is correct, newCapacity is 50% more than oldCapacity

在 Java 6 newCapacity 计算为

In Java 6 newCapacity is calculated as

int newCapacity = (oldCapacity * 3)/2 + 1;

这就是 Java 等开源语言的美妙之处,您可以查看实现 - 如果它不符合您的要求,您可以实现自己的.

This is the beauty of an open source language such as Java, you can see the implementation - if it doesn't fit your requirements, you can implement your own.

这篇关于ArrayList 容量增量公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 12:25