How does size( ) works in java's ArrayList class?

雨燕双飞 提交于 2019-12-12 16:28:51

问题


So, in order to get the most efficient code, I really wanted to know how does the size() method in Java ArrayList work... Does it count every element, going through all the positions, like a simple list? or does it just gets the size by the last index registered?

Thanks in advance!


回答1:


Never hurts to look in the source code:

public int size() {
    return size;
}

It returns an instance variable - pretty damn fast.




回答2:


As of the latest Java7, it does a little more than read a member field value:

public int size() {
    checkForComodification();
    return this.size;
}

private void checkForComodification() {
    if (ArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}



回答3:


In ArrayList there's an int attribute for storing the current size (say, called size). Clearly, calculating the size of an array list should be an O(1) operation, for efficiency. Even in a data structure such as a LinkedList (a double-linked list) the size is kept updated in an attribute, to avoid having to calculate it each time it's needed. To see it more clearly, take a look at the source code in OpenJDK, there you'll find this:

 /**
  * The size of the ArrayList (the number of elements it contains).
  *
  * @serial
  */
  private int size;

 /**
  * Returns the number of elements in this list.
  *
  * @return the number of elements in this list
  */
  public int size() {
      return size;
  }



回答4:


According to the source code for ArrayList, the size() method returns a private variable named size, which is just a counter that is incremented on each add.




回答5:


It reads a field variable. Java 1.6's ArrayList.size():

/**
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
    return size;
}


来源:https://stackoverflow.com/questions/15512508/how-does-size-works-in-javas-arraylist-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!