Friday, 26 April 2019

TreeMap Internal Working


Internal working of Tree Map: -

TreeMap doesn’t use Hashing like HashMap. It uses RED BLACK Tree data structure.
Each node in tree will have three references i.e. its parentright and left element.

·         The left element will always be less than parent.
·         The right element will always be greater than OR equal to parent.

The comparison of Objects is done by natural order using comparable interface.



Here we can insert multiple null values, but no null keys, if we insert null key that it will throw NullPointer exception.
package test;

import java.util.Map;
import java.util.TreeMap;

public class MainTest {
       public static void main(String... args) throws Exception {
              Map<Integer, String> treeMap = new TreeMap<>();
              treeMap.put(1, null);
              treeMap.put(5, null);
              treeMap.put(3, null);
       }
}

1 comment: