Skip to content
Advertisement

How to find the index of an element in a TreeSet?

I’m using a TreeSet<Integer> and I’d quite simply like to find the index of a number in the set. Is there a nice way to do this that actually makes use of the O(log(n)) complexity of binary trees?

(If not, what should I do, and does anyone know why not? I’m curious why such a class would be included in Java without something like a search function.)

Advertisement

Answer

As @Yrlec points out set.headSet(element).size will returns 0 though there is no this element in the set. So we’d better check:

JavaScript

Here is a test case to show the problem:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement