Java: For-Each loop and references [duplicate]

Java works a little bit different than many other languages. What o is in the first example is simply a reference to the object.

When you say o = new MyObject(), it creates a new Object of type MyObject and references o to that object, whereas before o referenced objects[index].

That is, objects[index] itself is just a reference to another object in memory. So in order to set objects[index] to a new MyObject, you need to change where objects[index] points to, which can only be done by using objects[index].

Image: (my terrible paint skills :D)

enter image description here

Explanation:
This is roughly how Java memory management works. Not exactly, by any means, but roughly. You have objects, which references A1. When you access the objects array, you start from the beginning reference point (A1), and move forward X blocks. For example, referencing index 1 would bring you to B1. B1 then tells you that you’re looking for the object at A2. A2 tells you that it has a field located at C2. C2 is an integer, a basic data type. The search is done.

o does not reference A1 or B1, but C1 or C2. When you say new ..., it will create a new object and put o there (for example, in slot A3). It will not affect A1 or B1.

Let me know if I can clear things up a little.

Leave a Comment