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.
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.
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.
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.
set.tailSet(obj).first();
does what you want.
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). Set
s are not really intended for lookup.
For the FooKey
example, FooKey
would be a simple immutable class that just contains the two String
s and is Comparable
. Finding the value of Foo
for two String
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With