java - 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;
}
解决方案
我不知道为什么以及会发生什么
您正在创建另一个数组,为其他元素提供更多空间。数组在 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
仍将引用新数组。
推荐阅读
- r - 如何从R中的密度范围内选择数据
- r - 变量名列表的非标准评估
- python - python中A1符号单元格值的参数化
- spring-data-jpa - 我正在尝试将“spring-data-jpa-datatables”作为 maven 依赖项引入我的项目,但是在启动服务器时遇到了其他几个错误
- c# - 在继续之前检查前两个字符的 return 语句
- c# - 如何在 WPF 视图中获取无效值
- reactjs - 动态加载组件以从外部 url 响应本机应用程序
- java - 了解 perf.map
- c# - ToolStripDropDown 在底层控制之前捕获 MouseeDown
- ios - IOS/Objective-C:多个CGAffineTransformation的动画