Time complexity of contains(Object o), in an ArrayList of Objects

前端 未结 4 1038
时光说笑
时光说笑 2020-12-01 10:04

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

4条回答
  •  Happy的楠姐
    2020-12-01 11:02

    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.

提交回复
热议问题