我们可以在java中调整数组的大小吗? [英] can we resize an array in java?
问题描述
我们可以在java中调整数组大小吗?如果没有,请解释一下:
can we resize an array in java? if not, explain this:
int arr[] = new int[1];
arr[0]=-10;
//arr[1]=1;
arr=new int[2]; //Explain this
arr[0]=-1;
arr[1]=1;
System.out.println(arr[0]+" "+arr[1]);
推荐答案
就我而言,调整阵列大小是不可能的关注。
Resizing an array is impossible, as far as I'm concerned.
要理解代码的工作原理,您需要了解数组是引用类型。 arr
包含对实际数组的引用,如下所示:
To understand why your code works, you need to understand that arrays are reference types. arr
holds an reference to the actual array, like this:
holds points to
arr ----------> reference -----------> array object
在这一行:
arr=new int[2];
你最后没有对数组对象做任何事情。你基本上是在说:
You are not doing anything to the array object at the very end there. You're basically saying:
嘿
arr
。我不希望你再持有那个引用。放开并按住此引用(这是一个长度为2的数组)!
Hey
arr
. I don't want you to hold that reference anymore. Let go and hold this reference (which is an array with length 2)!
会发生什么那个长度为1的原始数组对象呢?您询问。这就是GC到位的地方。在某些时候,会收集没有引用指向的对象。
"What happens to the original array object with length 1 then?" you asked. This is where the GC comes into place. At some point, objects that has no reference pointing to, are collected.
这篇关于我们可以在java中调整数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!