Returning an element from a TreeSet using binary search

exent picture exent · Apr 5, 2011 · Viewed 12.9k times · Source

In TreeSet there is a method called contains that returns true if an element is in the set. I assume that this method uses binary search and does not iterate through all the elements in ascending order. Am I right?

I have a TreeSet that contains objects of a class that uses two String instance variables to distinguish it from other objects of the same class. I want to be able to create a method that searches the TreeSet by comparing the objects two instance variables (using get methods of course) with two other String variables and if they are equal, return the element. If the instance variables are less than go to the first element in the right subtree or if they are greater search in the left subtree etc. Is there a way to do this?

I know I could just store the objects in an ArrayList and use binary search to find the object, but this wouldn't be as fast as just searching the TreeSet.

Answer

greg picture greg · Aug 30, 2011
set.tailSet(obj).first();

does what you want.