Collections.binarySearch() vs. List indexOf()

前端 未结 3 1435
既然无缘
既然无缘 2021-01-02 05:26

I have a list of more than 37K items, and I already implemented hashCode(), equals(), so I wonder Collections.binarySearch() can help

相关标签:
3条回答
  • 2021-01-02 06:01

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

    0 讨论(0)
  • 2021-01-02 06:07

    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().

    0 讨论(0)
  • 2021-01-02 06:09

    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.

    0 讨论(0)
提交回复
热议问题