开发者

Collections.binarySearch() vs. List indexOf()

I have a list of more than 37K items, and I already implemented hashCode(), equals(), so I wonder Collections.binarySearch() can hel开发者_JAVA百科p improve the performance and faster than indexOf() method.


If your collection is sorted, binarySearch() will be O(log n) as opposed to indexOf()'s O(n) and you will definitely see an improvement.


in order for binarySearch() to work, your list must be sorted. equals() and hashCode() have nothing to do with sorting. your objects need to be Comparable, or you must have a relevant Comparator. either way, you must sort the List first.

and yes, assuming the list is sorted, then you will probably get better performance from binarySearch() as compared to indexOf().


You'll get even better performance by using a HashSet. That will take more space, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜