gpt4 book ai didi

Java:调整大小方法,有人能解释一下吗?

转载 作者:行者123 更新时间:2023-12-02 13:30:55 24 4
gpt4 key购买 nike

我不确定这个方法是如何工作的。我的理解是,我们创建一个临时数组,其大小是 theItems.length 的两倍(theItems 是另一个数组)。之后,我们将项目复制到临时数组,最后我们编写 theItems = temp; (我不确定为什么以及发生了什么)(这是否意味着 theItems 的大小也增加了一倍?)。我们不能在不使用 temp 的情况下将 theItems 的大小加倍吗?

private void resize() {
String[] temp = new String[theItems.length*2];
for (int i=0 ; i < noOfItems ; i++){
temp[i]=theItems[i];
}
theItems=temp;
}

最佳答案

I am not sure why and what happens

您正在创建另一个数组,为其他元素提供更多空间。 Java 中的数组有固定的大小;一旦创建,就无法更改。这里,新数组的长度是旧数组的两倍。然后一个简单的 for 循环复制元素引用。

does it mean that theItems double its size too?

不,数组引用 theItems 被重新分配给刚刚创建的更大的新数组。

Can't we double the size of theItems without using temp?

您可以将 theItems 替换为新数组,但是这样您就丢失了对包含您想要保留的所有项目的原始数组的引用,因此这没有用。

发生的情况是这样的:

  1. 初始条件。

    theItems -> ["one", "two", "three"]
  2. 已创建新数组。

    theItems -> ["one", "two", "three"]

    temp -> [null , null , null , null, null, null]
  3. 已复制项目。

    theItems -> ["one", "two", "three"]

    temp -> ["one", "two", "three", null, null, null]
  4. 变量theItems被重新赋值。

    theItems \       ["one", "two", "three"]  <- will be garbage collected.
    |
    temp --+> ["one", "two", "three", null, null, null]

变量 temp 将超出范围,但 theItems 仍将引用新数组。

关于Java:调整大小方法,有人能解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52412590/

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