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?
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 */);
}
See more on this question at Stackoverflow