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:java

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?less

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

 

Answer:this

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

Because elementData method use more then one place:orm

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

Do these extra rounds lead to worse performance?element

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 method.rem

相關文章
相關標籤/搜索