Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an element from a TreeSet using binary search

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.

like image 640
exent Avatar asked Apr 05 '11 21:04

exent


People also ask

How do I retrieve an element from a TreeSet?

So there are many ways to get the element by index: Converting TreeSet to array by traversing through the whole TreeSet and adding the element to array one by one. Converting TreeSet to array using . toArray() method. Converting TreeSet to ArrayList.

Is a TreeSet a binary search tree?

The TreeSet uses a self-balancing binary search tree, more specifically a Red-Black tree. Simply put, being a self-balancing binary search tree, each node of the binary tree comprises of an extra bit, which is used to identify the color of the node which is either red or black.

How do you reverse a TreeSet in Java?

To sort TreeSet in descending order, use the descendingSet() method in Java. The descendingSet() method is used to return a reverse order view of the elements contained in this set.


2 Answers

set.tailSet(obj).first();

does what you want.

like image 61
greg Avatar answered Sep 23 '22 04:09

greg


Rather than using a TreeSet, you could store your objects in a TreeMap<Foo, Foo> or TreeMap<FooKey, Foo> (if you can't easily create a new actual Foo each time you want to search). Sets are not really intended for lookup.

For the FooKey example, FooKey would be a simple immutable class that just contains the two Strings and is Comparable. Finding the value of Foo for two Strings would then be a simple matter of treeMap.get(new FooKey(firstString, secondString)). This does of course use the tree traversal you want to find the value.

like image 39
ColinD Avatar answered Sep 21 '22 04:09

ColinD