简体   繁体   English

将列表转换为固定大小的数组

[英]converting list to an array of fixed size

Could anyone please explain me why this code snippet works? 有人可以解释一下为什么这段代码片段有效吗?

Object[] op = new Object[0];

ArrayList r = new ArrayList();
r.add("1");
r.add("3");
r.add("5");
r.add("6");
r.add("8");
r.add("10");

op = r.toArray();
System.out.println(op[3]);

This prints out 6. I know that you can convert list to array but I was thinking that if the array is fixed size then you can't add further elements. 这打印出6.我知道你可以将列表转换为数组,但我想如果数组是固定大小,那么你不能添加更多的元素。 In this case the array op is with fixed size "0" so why/how are the list elements being added to the array? 在这种情况下,数组op的大小固定为“0”,那么为什么/如何将列表元素添加到数组中呢? Thanks 谢谢

You need to distinguish between the reference to your array object (that is Object[] op ) and the actual array object to which the reference points. 您需要区分对数组对象的引用 (即Object[] op )和引用指向的实际数组对象

With

Object[] op = new Object[0];

you are creating an array of size 0 and assign it to the op reference. 您正在创建一个大小为0的数组并将其分配给op引用。

But then, with 但随后,随着

op = r.toArray();

you are assigning a new array object to the op reference. 您正在为op引用分配新的数组对象。 This new array object has been created by the toArray() method with the appropriate size. 这个新的数组对象是由toArray()方法创建的,具有适当的大小。

The earlier array object which was created with new Object[0]; new Object[0];创建的早期数组对象new Object[0]; is now dangling and subject to garbage collection. 现在正在悬空并受到垃圾收集。

For the same reason that this code prints out X instead of ABC: 出于同样的原因,此代码打印出X而不是ABC:

String s = "ABC";
String t = "XYZ";
s = t.substring(0, 1);
System.out.println(s);

You're reassigning the value of op, and the new value has nothing to do with the old value. 您正在重新分配op的值,而新值与旧值无关。

You misunderstood one important thing here. 你在这里误解了一件重要的事情。 Java identifiers are only pointers to objects, not objects themselves. Java标识符只是指向对象的指针,而不是对象本身。

Here when you do 当你这样做

Object[] op = new Object[0];

you create a new instance array with a fixed size of 0, and you point the identifier "op" to it. 您创建一个固定大小为0的新实例数组,并将标识符“op”指向它。

But when you later do 但是当你以后做的时候

op = r.toArray();

you just overwrite where your former identifier point to. 你只是覆盖你以前的标识符指向的位置。 You lose the reference to your first array that will be garbaged collected. 您将失去对将要收集的第一个阵列的引用。 "op" desgin now a new array, your former one just disappear. “op”desgin现在是一个新阵列,你的前一个刚刚消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM