问题
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