ArrayDeque.allocateElements 的实现(按位运算)
我正在查看 Java 1.6 的 Java.Util.ArrayDeque (队列实现)的源代码,并偶然发现 allocateElements() ,它应该根据给定的元素数量
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = (E[]) new Object[initialCapacity];
}
调整后备数组的大小:What is the Purpose of ORinginitialCapacity with itself -r转移?
I was looking at the source of Java 1.6's Java.Util.ArrayDeque (a queue implementation) and stumbled on allocateElements() which should size the backing array according to the given number of elements:
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = (E[]) new Object[initialCapacity];
}
What is the purpose of ORing initialCapacity with itself-rshifted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它看起来像
ArrayDeque
< /a> 长度“始终是 2 的幂”,以简化可以“在addX()
方法内”调用的doubleCapacity()
的实现。特别是附录:这是一个示例,它检查在递增到下一个较大的 2 的幂之前在临界值处计算的容量。
安慰:
It looks like the
ArrayDeque
length "is always a power of two" in order to simplify the implementation ofdoubleCapacity()
, which may be invoked "within anaddX()
method." In particular,Addendum: Here's an example that examines the calculated capacity at critical values just before incrementing to the next larger power of two.
Console:
等于:
它将把低于第一个的所有位设置为 1。
equals to:
It will set all bits lower than the first to 1.