48

As the title says, I was wondering what the time complexity of the contains() method of an ArrayList is.

Samuel
  • 18,286
  • 18
  • 52
  • 88

4 Answers4

58
O(n)

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.

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html

davin
  • 44,863
  • 9
  • 78
  • 78
14

it's O(n) for ArrayList

Bala R
  • 107,317
  • 23
  • 199
  • 210
3

If you look into the source code for ArrayList and check its contains method it looks as below:

public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

contains delegates the check to the indexOf method. So, if we check the indexOf implementation it is as follows:

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

As it can be seen from the code, in order to find an index of a given element, one, in the worst case, must iterate through the whole array. As a size of the array grows and so does the search time by an element. Hence, the time complexity of contains method is O(n), where n is the number of elements in the list.

Anatolii
  • 14,139
  • 4
  • 35
  • 65
1

its O(n). contains(Object o) is implemented on indexOf() which takes O(n). So complexity of contains(Object o) is defensively O(n)

Here are some other if you need:

add() - O(1)
add(index, element) – O(n)
get() – O(1)
set() – O(1)
remove() –  (n)
indexOf()` – O(n)
Tushar Monirul
  • 4,944
  • 9
  • 39
  • 49
  • 1
    Thanks for your answer, two small comments: 1) I am not sure you need to specify "defensively", that is already implied by using `O` notation; 2) technically `add` is not really `O(1)`, in the worst case it is linear, but it runs in *amortized* constant time (see the answer by @davin). – Samuel Jun 06 '20 at 18:00