David Lefaivre
David Lefaivre

Reputation: 211

How Java TreeSet are implemented

I was wondering how a TreeSet is implemented in Java. In fact, I was wondering, is a TreeSet using, under the hood, a balancing tree, or is it using an array ?

In other word, when I am adding an element to my treeSet, I know it will be ordered, but will it will be:

It has been a while since I study data structure, so just let's me know if my question make no sens or is not well explained.

Thank you

Upvotes: 3

Views: 3183

Answers (1)

Ollin Boer Bohan
Ollin Boer Bohan

Reputation: 2401

Java's TreeSet uses a TreeMap, which is backed by a red-black tree. So, mostly the second option, but red-black trees are self-balancing so you won't run into the pathological "linear" case even if you insert elements in ascending/descending order.

Upvotes: 2

Related Questions