Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the contains() method in Java ArrayList use binary search?

Does the contains() method in Java ArrayList use binary search? Or do I need to use Collections to do this instead?

like image 860
John Roberts Avatar asked Jan 14 '23 14:01

John Roberts


1 Answers

No, you need to use Collections to use binary search, usually after sorting it. An ArrayList doesn't know anything about its ordering, and you have to know a list is sorted before you can use binary search.

Alternately, you could use TreeSet, which is as efficient as using a binary search.

like image 80
Louis Wasserman Avatar answered Jan 17 '23 18:01

Louis Wasserman