Almost all methods in CopyOnWriteArrayList use getArray() insted of direct appeal to array. Is there a reason for this behavior? For example :
public int size() {
return getArray().length;
}
or
public int indexOf(Object o) {
Object[] elements = getArray();
return indexOf(o, elements, 0, elements.length);
}
"Why did they design it that way" questions are always a matter of conjecture. This one is as well ... unless the code's author (Doug Lea) were to explain his thinking to us.
However, I think that the primary reason is stylistic.
The array
variable is declares as private
.
The getArray
method is declared as package private with the comment:
// Gets the array. Non-private so as to also be accessible
// from CopyOnWriteArraySet class.
If there wasn't a method, it would be necessary to declare the array
variable itself as package private. I think (and I suspect that Doug also thinks) that a package private getter is much better than a package private field. (For all the standard reasons.) And if the getter and setter exist, it is reasonable to use them.
The related question (Why setArray() method call required in CopyOnWriteArrayList) explains why there are calls to setArray
in apparently unnecessary places. But that's an orthogonal issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With