Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 help improve the performance and faster than indexOf() method.

like image 231
Truong Ha Avatar asked Apr 14 '11 17:04

Truong Ha


People also ask

What is collections binarySearch?

Collections. binarySearch() method is a java. util. Collections class method that returns position of an object in a sorted list.

Which collection is faster for searching in Java?

If you need fast access to elements using index, ArrayList should be choice. If you need fast access to elements using a key, use HashMap. If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).

Can you binary search an ArrayList?

In order to perform Binary Search on ArrayList with Java Collections, we use the Collections. binarySearch() method. If key is not present, the it returns ((insertion point) + 1) *(-1).

Does indexOf use binary search?

The indexOf method on List uses a linear search with O(n) time complexity. Binary search has O(log n) time complexity, which scales much better for large data sets if you are doing repeated lookups.


1 Answers

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.

like image 104
David Titarenco Avatar answered Oct 28 '22 07:10

David Titarenco