How does the java TreeSet explicitly function?

111 Views Asked by At

1) Can anyone please explain or point me toward a tutorial that will explain and give examples of how the TreeSet accomplishes it's task? More specifically, what is the written out code behind the class that allows it to function?

2) Also, can TS be used to sort an unsorted array of strings?

Thanks so much!

EDIT: For (2), I am attempting to initialize a string String[] names = strings {junk names...} and have them lexicographically sorted. Is TS the correct call to make? Or is there another direction I should look.

2

There are 2 best solutions below

1
On

In short TreeSet= Tree(for ordering) + Set(for avoiding duplicates). In java Comparator/Comparable is used to compare two object in treeset

For Details,you need to have look at TreeSet source code . Here is the link Source Code

2
On

A TreeSet is backed by a TreeMap, which is a red-black tree -http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/TreeMap.java#TreeMap

In treeset object stored in sorted manner, using compareTo() method. So you can use this to get sorted array.