Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Parameter and Enhanced For Loop copy issue

assume i have code like this;

public void insert(Student[] stus)
{
    int count = 0;
    for(Student s: stus)
    {
    s.setId( bla bla);
    stus[count].setId(bla bla) // is this line needed?
    count++;
    }
}

So if i change anything on s from enhanced for loop, can i see the change in stus array also? How does enhanced for loop copy works in parameters or other things etc?

like image 669
Mert Serimer Avatar asked Sep 11 '26 06:09

Mert Serimer


2 Answers

The enhanced for loop doesn't create a copy of the elements of the Collection or array you are iterating over, and therefore s.setId() and stus[count].setId() would update the same Student instance.

stus[count].setId(bla bla) is not needed, as s.setId(bla bla) does the same.

like image 193
Eran Avatar answered Sep 12 '26 19:09

Eran


Yes - s is just a variable which contains a value copied from stus. That value is a reference to an object - changes made via s will still be visible from stus. It's only the reference that's copied. So your loop can just be:

for (Student s : stus) {
    s.setId(...);
}

No need for the count at all unless it's part of the computation of the ID. If it is part of that computation, I'd just use a regular for loop instead:

for (int i = 0; i < stus.length; i++) {
    s.setId(/* some expression involving i */);
}
like image 33
Jon Skeet Avatar answered Sep 12 '26 20:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!