Collections.binarySearch () vs. List indexOf ()

I have a list of more than 37K elements, and I already implemented hashCode() , equals() , so I'm wondering Collections.binarySearch() can help improve performance faster than the indexOf() method.

+7
source share
3 answers

If your collection is sorted, binarySearch() will be O (log n) unlike indexOf() O (n), and you will definitely see an improvement.

+15
source

To work with binarySearch (), your list must be sorted. equals () and hashCode () have nothing to do with sorting. your objects must be comparable, or you must have an appropriate comparator. in any case, you must first sort the list.

and yes, provided the list is sorted, then you are likely to get better performance from binarySearch () compared to indexOf ().

+8
source

You will get even better performance using a HashSet. It takes up more space.

+3
source

All Articles