创建后更改数组大小 [英] Array size changing after creation
本文介绍了创建后更改数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以解释这里发生的事情.我的印象是,数组的大小一旦创建并声明就无法更改.
can anyone explain whats happening here. I was under the impression that an array's size can't be changed once its been created and declared.
public class ArrayManipulation
{
public static void main(String[] args)
{
int a[] = {1, 2, 3};//new int[3];
int b[] = new int[a.length-1];
System.out.print("a = ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
for (int i = 0; i < b.length; i++)
b[i] = a[i];
//This is the bit I am confused about.. I was expecting an error here
a = b;
System.out.print("a = ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}
推荐答案
数组是对象,是的,一旦创建,数组的大小就不会改变.
Arrays are objects, and yes, once they are created their size doesnt change.
a= b;
您将a
引用指向b
对象.因此,a
所引用的初始对象仍在VM中,直到被垃圾回收为止.
you are pointing a
reference to b
object. So your initial object that a
was referencing is still in VM until it s garbage collected.
但是您的数组大小没有变化,但是您引用的对象现在指向一个差异数组/对象
But your array size didnt change but you reference is pointing to a differet array/object now
这篇关于创建后更改数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文