Does the ArrayList's contains() method work faster if the ArrayList is ordered?

Guillermo Mosse :

I suspect it doesn't. If I want to use the fact that the list is ordered, should I implement my own contains() method, using binary search, for example? Are there any methods that assume that the list is ordered?

This question is different to the possible duplicate because the other question doesn't ask about the contains() method.

Stephen C :

Does the ArrayList's contains() method work faster if the ArrayList is ordered?

It doesn't. The implementation of ArrayList does not know if the list is ordered or not. Since it doesn't know, it cannot optimize in the case when it is ordered. (And an examination of the source code bears this out.)

Could a (hypothetical) array-based-list implementation know? I think "No" for the following reasons:

  1. Without either a Comparator or a requirement that elements implement Comparable, the concept of ordering is ill-defined.

  2. The cost of checking that a list is ordered is O(N). The cost of incrementally checking that a list is still ordered is O(1) ... but still one or two calls to compare on each update operation. That is a significant overhead ... for a general purpose data structure to incur in the hope of optimizing (just) one operation in the API.

But that's OK. If you (the programmer) are able to ensure (ideally by efficient algorithmic means) that a list is always ordered, then you can use Collections.binarySearch ... with zero additional checking overhead in update operations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112995&siteId=1