M
M
Mimocodil2021-07-24 10:00:18
Java
Mimocodil, 2021-07-24 10:00:18

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

1 answer(s)
S
Sergey Gornostaev, 2021-07-24
@Ezekiel4

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 question

Ask a Question

731 491 924 answers to any question