Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

java - 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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I poked around TreeSet and its interfaces for a while, and the best way I found to get the index of an element is:

set.headSet(element).size()

headSet(element) returns the sub-TreeSet of elements less than its argument, so the size of this set will be the index of the element in question. A strange solution indeed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...