Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of tree is used in Java's TreeSet and TreeMap?

Are they AVL trees, red-black trees, or something else?

like image 472
Craig P. Motlin Avatar asked Aug 27 '10 01:08

Craig P. Motlin


People also ask

Which tree is used in TreeSet?

In this implementation, objects are sorted and stored in ascending order according to their natural order. The TreeSet uses a self-balancing binary search tree, more specifically a Red-Black tree.

Is TreeMap a binary tree?

In Java, a TreeMap is a red-black tree, which is a self-balancing binary search tree.

What are TreeSet and TreeMap?

TreeSet implements SortedSet in Java. TreeMap implements Map Interface in Java. 2. TreeSet stored a single object in java. TreeMap stores two Object one Key and one value.

What is the use of TreeSet and TreeMap in Java?

TreeMap is used to keep mappings between key and values in sorted order while TreeSet is used to keep just one element in sorted order. TreeSet also doesn't allow duplicates but TreeMap does allow duplicate values. If you find any other significant difference between TreeMap and TreeSet then please post as a comment.


2 Answers

Red-black trees as described in the first line of the javadoc.

  • Tree Map
  • Tree Set
like image 189
Kru Avatar answered Oct 07 '22 18:10

Kru


From the java.util.TreeMap<K,V> documentation:

A Red-Black tree based NavigableMap implementation.

For questions like these, you should always first consult the documentation. The API shouldn't describe ALL of the inner-workings of a class, but elementary informations such as general data structures and algorithms used are usually documented.


Other Java Collections Framework trivias

These are all little trivias that are also clearly documented:

  • TreeSet is implemented with a TreeMap
  • HashSet is implemented with a HashMap
  • Collections.sort uses modified mergesort
  • Map<K,V> is not a Collection<?>
  • ArrayList doesn't specify exact growth policy (unlike, say, Vector)

Related questions

  • Why does java.util.Arrays.sort(Object[]) use 2 kinds of sorting algorithms?
  • Why does the Java Collections Framework offer two different ways to sort?
  • Why doesn't Java Map extends Collection?
like image 45
polygenelubricants Avatar answered Oct 07 '22 17:10

polygenelubricants