首页 > 解决方案 > Java:调整大小方法,有人可以解释一下吗?

问题描述

我不确定这种方法是如何工作的。我的理解是,我们创建了一个临时数组,其大小是theItems.length(theItems 是另一个数组) 的两倍。之后,我们将项目复制到 temp 数组中,最后我们编写 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;
}

标签: javaarraysresize

解决方案


我不知道为什么以及会发生什么

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

这是否意味着 theItems 的大小也翻了一番?

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

我们不能在不使用 temp 的情况下将 theItems 的大小加倍吗?

您可以只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仍将引用新数组。


推荐阅读