3

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. In this case the array op is with fixed size "0" so why/how are the list elements being added to the array? Thanks

3 Answers 3

6

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.

With

Object[] op = new Object[0];

you are creating an array of size 0 and assign it to the op reference.

But then, with

op = r.toArray();

you are assigning a new array object to the op reference. This new array object has been created by the toArray() method with the appropriate size.

The earlier array object which was created with new Object[0]; is now dangling and subject to garbage collection.

Sign up to request clarification or add additional context in comments.

1 Comment

oh yes. I totally forgot that the array variables are also reference variables. Thanks
1

For the same reason that this code prints out X instead of 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.

Comments

1

You misunderstood one important thing here. Java identifiers are only pointers to objects, not objects themselves.

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.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.