views:

1044

answers:

4

Is ArrayList an array or a list in java? what is the time complexity for the get operation, is it O(n) or O(1)?

+5  A: 

It's implementation is done with an array and the get operation is O(1).

javadoc says:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

tangens
+2  A: 

To be pedantic, it's a List backed by an array. And yes, the time complexity for get() is O(1).

Carl Smotricz
+6  A: 

An ArrayList in Java is a List that is backed by an array.

The get(index) method is a constant time, O(1), operation.

The code straight out of the Java library for ArrayList.get(index):

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

Basically, it just returns a value straight out of the backing array. (RangeCheck(index)) is also constant time)

jjnguy
+1 for being the best answer so far
dfa
+1  A: 

As everyone has already pointed out, read operations are constant time - O(1) but write operations have the potential to run out of space in the backing array, re-allocation, and a copy - so that runs in O(n) time, as the doc says:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

In practice everything is O(1) after a few adds, since the backing array is doubled each time it's capacity is exhausted. So if the array starts at 16, gets full, it's reallocated to 32, then 64, 128, etc. so it scales okay, but GC can hit up during a big realloc.

Kristopher Ives
It's a little off-topic, but I would hate for someone to get confused and not really notice the emphasis on **get** operations.
Kristopher Ives
In the JDK code I'm looking at (1.6.0_17) the new capacity is actually calculated as (oldCapacity * 3)/2 + 1.
Adamski
Quibble about the first sentence, which seems to imply that write operations run in O(n) time. That's not what the doc says, it says that *adding n elements requires O(n)*. For individual elements, insertion time is still O(1). The re-allocation, copy etc. just make it a somewhat "bigger" O(1).
Carl Smotricz
You can avoid the expansion steps if you tell the constructor how big it should be from the beginning. (if you know)
Thorbjørn Ravn Andersen