1. 程式人生 > >Why having both get and elementData methods for an ArrayList?

Why having both get and elementData methods for an ArrayList?

開發十年,就只剩下這套架構體系了! >>>   

I am studying the implementation of ArrayList in java.util, and plenty of methods seem to be useless for me, they just make the code more difficult to read. For instance:

public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}


 E elementData(int index) {
    return (E) elementData[index];
}

Why not cast elementData in public E get(int index) directly?

Do these extra rounds lead to worse performance? (besides extra work and worse readability)

 

Answer:

Why not cast elementData in public E get(int index) directly?

Because elementData method use more then one place:

public E set(int index, E element) {
   ...
   E oldValue = elementData(index);

public E remove(int index) {
   ...
   E oldValue = elementData(index);

public E set(int index, E e) {
   ...
   E oldValue = ArrayList.this.elementData(offset + index);

public E get(int index) {
   ...
   return ArrayList.this.elementData(offset + index);

It's ugly and bad Java prictise to write (E) elementData[index] everywhere, for example (E) ArrayList.this.elementData[offset + index], small method in Java better then copypast.

Do these extra rounds lead to worse performance?

Nop, JVM can optimize this small method's call and divided to small method in Java better then saving a irreducible small time for calling m