0

I am new to java, especially java collections. Java data-structure TreeMap does not have any methods (like getChildren, getParent) to suggest that it holds a hierarchical structure. What is the significance of word tree in the class-name?

Manojkumar Khotele
  • 963
  • 11
  • 25

4 Answers4

1

In two words, TreeMap means that it is a Map implementation where the data is stored in a tree-like structure. This leads to the fact that elements are sorted by their keys (TreeMap implements SortedMap).

Here is good visualisation of red-black tree.

Other types of maps in Java are HashMap and LinkedHashmap. You can find differences here.

Community
  • 1
  • 1
Gaket
  • 6,533
  • 2
  • 37
  • 67
0

The "tree" part gives away an implementation detail of the class. According to the documentation, TreeMap is

A Red-Black tree based NavigableMap implementation.

The name OrderedMap or SortedMap would probably be better, but "tree" is good enough to convey the way the class works to its users.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

A TreeMap is essentially a Red-black tree which is a balanced search tree. The main purpose of this tree is ensure O(lg(n)) lookup and not modelling a hierarchies.

If you look at the code of TreeMap, you will find that it has TreeMap.Entry which is defined as follows.

 static final class Entry<K,V> implements Map.Entry<K,V> {
    K key;
    V value;
    Entry<K,V> left;
    Entry<K,V> right;
    Entry<K,V> parent;
    boolean color = BLACK;
  ..
 }

But OOP tells us that implementation details shouldn't be exposed

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

The data structure is principally a map, not a tree. But the map is implemented using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. As it is a map to the user, you don't need to get parent of any node in the tree, or its child, hence no getParent or getChildren function is available.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90