flapas
flapas

Reputation: 583

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

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!

Upvotes: 4

Views: 3046

Answers (5)

Óscar López
Óscar López

Reputation: 236150

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;
  }

Upvotes: 1

Amir Afghani
Amir Afghani

Reputation: 38561

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();
}

Upvotes: 2

Steve Kuo
Steve Kuo

Reputation: 63134

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;
}

Upvotes: 0

rgettman
rgettman

Reputation: 178343

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.

Upvotes: 0

Perception
Perception

Reputation: 80633

Never hurts to look in the source code:

public int size() {
    return size;
}

It returns an instance variable - pretty damn fast.

Upvotes: 5

Related Questions