Moyo2k
Moyo2k

Reputation: 137

Why can you change field variables with an enhanced for loop but you cannot initialiaze objects?

I recently learned that you cannot initialize objects using an enhanced for loop in Java because of the way an enhanced for loop works by creating a 'dummy' object from the object and then performing whatever the code states using the dummy object

But this prompted me to attempt to change field variables inside objects using an enhanced for loop and surprisingly the code changed the field variables in the objects. Can anyone please explain to me how this works because to my understanding no change should occur to the objects for the same reason you can't initialize objects using the enhanced for loop. Clearly I have exposed a gap in my understanding here so can anyone help me out

Upvotes: 1

Views: 2116

Answers (3)

AmitS
AmitS

Reputation: 180

In java the objects you see are not objects but in fact object references.
An object reference is just an reference to the object in RAM. For example.

Person p1;
Person p2;
p1 = new Person();  // p1 now has an reference to an Person object
p2 = p1;  // Now p2 and p1 point to the same object

Now, if we made a change to the p2's object, that change would be reflected to p1's object because they refer to the same object.

For example.

p2.setHeight(50);
p1.setHeight(90);
System.out.println(p2.getHeight());

The code snippet above would print out 90, not 50. Because first the object's height was set to 50, but then the objects height was set to 90(using some other object reference).

Going back to your question.

for(Person p : peopleArray)
{
    // more code
}

In every cycle of the for loop, an object reference p is created and refers to the same object that an object reference in peopleArray refers to.

Upvotes: 2

Lews Therin
Lews Therin

Reputation: 10995

Are you asking about this:

for (Animal a: animals)
{ 
 a=new Dog(); // wrong
}

If so, think of a as defined in this case as final Animal a. Therefore the reference variable is immutable. But the member fields of the objects (if any) are not necessarily immutable.

for (Animal a: animals)
{ 
  a.Name = "Jack"; //valid, if Name is a mutable member field.
}

Upvotes: 1

BitNinja
BitNinja

Reputation: 1487

In an enhanced for loop you are allowed to modify objects, but you are not allowed to change the data structure you are iterating through. This means you can change the fields of objects but you can't add or remove items from the data structure. Nor are you allowed set a whole new object to one that is already in the list. If you modify the list, there will be a ConcurrentModificationException thrown.

Upvotes: 1

Related Questions