Answer the question
In order to leave comments, you need to log in
Why is it copied to iterate over an array of objects?
I'm picking java src, in the ArrayList class I came across the code below (elementData is a transient Object[]). In it, before iterating, the array is copied into a new variable. Why did they do this if you can iterate over the original array?
public int indexOf(Object o) {
return indexOfRange(o, 0, size);
}
int indexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = start; i < end; i++) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = start; i < end; i++) {
if (o.equals(es[i])) {
return i;
}
}
}
return -1;
}
Answer the question
In order to leave comments, you need to log in
They do not copy the array itself, but a reference to it. They do this because other methods can change this link.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question