gpt4 book ai didi

java - 在堆栈中的动态数组中声明收缩函数

转载 作者:行者123 更新时间:2023-12-01 11:06:08 24 4
gpt4 key购买 nike

这是我的代码:

private void shrink(){ 
int length = top+1;
if(length<=MINCAPACITY || top<<2 >= length)
return;
length = length + (top<<1);
if(top < MINCAPACITY) length = MINCAPACITY;
int[] newstack = new int[length];
System.arraycopy(stackRep, 0 , newstack, 0 , top+1);
stackRep = newstack;
}

在我的书中,据说如果超过 3/4 为空,则此操作会将数组缩小一半。谁能向我解释一下这段代码是如何发生的?我怀疑这个操作发生在第一个if语句和length语句中?

最佳答案

Java 数组不能改变长度。其作用是计算新长度,创建该长度的新数组,并将旧数组中的内容复制到其中,然后使旧数组引用新数组。

int length = ... // this will be the new arrays length
int[] newstack = new int[length]; // this is the new array
System.arraycopy(stackRep, 0 , newstack, 0 , top + 1); // stuff is copied to the new array
stackRep = newstack; // old array is now the new array

不确定这是否能回答您的问题

编辑:

通过“改变长度的部分”,我假设您想知道它们的作用:<<>> 。它们是位移运算符,您可以找到关于它们的更详细的描述,例如 here .

基本上他们这样做:

  • x << n - 乘以x通过2的幂n
  • x >> n - 划分x通过2的幂n

所以10 << 12010 << 38010 >> 1510 >> 22 (这里失去了精度,因为这些运算符只是移位位)。

关于java - 在堆栈中的动态数组中声明收缩函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32931503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com