英文:
Resizing of ArrayDeque
问题
引用:ArrayDeque
的默认初始容量为 16。当大小超过容量时,它会按照2的幂增加(24、25、26等等)。
这是否意味着它的行为类似于 ArrayList
?每次大小超过容量时,都会有一个新的数组,旧元素会被复制到其中吗?我能否说 ArrayDequeue
和 ArrayList
的内部实现都是基于数组(正如它们的名称所示)?只是调整大小的方式不同?
英文:
Quote: Default initial capacity of ArrayDeque is 16. It will increase at a power of 2 (24, 25, 26 and so on) when size exceeds capacity.
Does this mean it behaves similar to ArrayList
? Each time size exceeds capacity there is new array where older elements are copied to? Can I say internal implementation of ArrayDequeue
and ArrayList
is array (as their name says)? Just the resizing differs?
答案1
得分: 1
是的,ArrayDeque
的行为与 ArrayList
类似:它在内部使用一个对象数组。如果容量不足,它会创建一个新的、更大的数组,并将项目从旧数组复制到新数组。
Java API 规范并不要求任何特定的调整大小行为。实际上,OpenJDK 中当前的实现在数组小于 64 时会将数组的大小加倍,否则会增长 50%:
// 如果较小,则加倍容量;否则增长 50%
int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
看起来,“加倍”行为是近似的:在第一次调整大小后,由于有“+2”,容量为 16+16+2 = 34。在第二次调整大小后,它变为 34+34+2 = 70。此后,数组在每次调整大小时增长 50%。
英文:
Yes ArrayDeque
behaves similarly to ArrayList
: Internally it uses an Object array. If the capacity is not enough, it creates a new, larger array, and copies items from the old array to the new.
The Java API specification does not require any particular resizing behavior. In fact the current implementation in OpenJDK doubles the size of the array if it's small (64), otherwise it grows by 50%:
// Double capacity if small; else grow by 50%
int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
It seems that the"doubling" behavior is approximate: thanks to the "+2" after the first resize the capacity is 16+16+2 = 34. After the second resize it's 34+34+2 = 70. After that the array increases by 50% in every resize.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论