Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why CopyOnWriteArrayList use getArray() to access an array reference?

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);
}
like image 557
Waka Waka Avatar asked Oct 31 '17 07:10

Waka Waka


Video Answer


1 Answers

"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.

like image 161
Stephen C Avatar answered Oct 31 '22 15:10

Stephen C