Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity for java ArrayList

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

like image 390
Hidayat Avatar asked Feb 02 '10 08:02

Hidayat


People also ask

What is the time complexity of ArrayList get method?

An ArrayList in Java is a List that is backed by an array . The get(index) method is a constant time, O(1) , operation.

Is ArrayList O of n?

ArrayList has O(n) time complexity for arbitrary indices of add/remove, but O(1) for the operation at the end of the list. LinkedList has O(n) time complexity for arbitrary indices of add/remove, but O(1) for operations at end/beginning of the List.

Is ArrayList size constant time?

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.


1 Answers

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)

like image 105
jjnguy Avatar answered Oct 05 '22 08:10

jjnguy