尚方宝剑之说
我不确定为什么会发生什么您正在创建另一个数组,为其他元素提供更多空间。数组在 Java 中具有固定大小;一旦创建,就无法更改。在这里,新数组的长度是旧数组的两倍。然后一个简单的for循环复制元素引用。这是否意味着 theItems 的大小也翻了一番?不,数组引用theItems被重新分配给刚创建的新的、更大的数组。我们不能在不使用 temp 的情况下将 theItems 的大小加倍吗?您可以只theItems用一个新数组替换,但随后您就丢失了对包含要保留的所有项目的原始数组的引用,因此这没有用。这是发生的事情:初始条件。theItems -> ["one", "two", "three"]已创建新阵列。theItems -> ["one", "two", "three"]temp -> [null , null , null , null, null, null]已复制项目。theItems -> ["one", "two", "three"]temp -> ["one", "two", "three", null, null, null]变量theItems被重新分配。theItems \ ["one", "two", "three"] <- will be garbage collected. |temp --+> ["one", "two", "three", null, null, null]该变量temp将超出范围,但theItems仍会引用新数组。