TreeMap Class in Java
In this post I am going to explain about some interesting
difference between TreeMap class in Java 6 and Java 7 Collections. Before we
are moving to TreeMap class we should know about the Map interface in Java
Collection.
Map :
- If we want to represent a group of objects as key-value pairs then we should go for Map in.
- Both keys and values are objects in Map.
- Duplicate keys are not allowed but values can be duplicated.
- There is no relationship between Collection (for group of individual objects) and Map (for group of key-value pairs).
- Each key-value pair is called as Entry.
6. There
are two main Classes which is used often in our java program
i) HashMap ii) TreeMap
Here I am going to explain about
TreeMap Class.
TreeMap:
- A class which implements the Sorted Map Interface.
- TreeMap implements the RED-BLACK Tree data structure concepts
- Insertion order is not preserved, because the all the entries are inserted based on some sorting order of keys.
- If we are depending on default natural ordering then the keys should be Homogeneous and Comparable. Otherwise we will get the ClassCastException. Example :
Case 1: (If Key doesn’t implement the
comparable Interface)
Output :
Output :
homogeneous and comparable.
6. There are no restrictions on values they can be Heterogeneous and non -comparable.
7. Duplicate keys are not allowed but duplicate values are allowed.
6. There are no restrictions on values they can be Heterogeneous and non -comparable.
7. Duplicate keys are not allowed but duplicate values are allowed.
Comparison of TreeMap in Java 6 and Java 7 (based on Null acceptance)
Java 6
1. Insert
an Entry with null key in empty TreeMap is allowed. But after inserting this
entry if we
are trying to insert any other Entry we will get NullPointerException.(i.e
TreeMap allows Null
key only once if it is an empty TreeMap)
2. Insert an Entry with null key in non-empty TreeMap we will get NullPointerException.
3. In TreeMap there are no restrictions on NULL values. We can use NULL values any no of
2. Insert an Entry with null key in non-empty TreeMap we will get NullPointerException.
3. In TreeMap there are no restrictions on NULL values. We can use NULL values any no of
times in Map.
Example :
Output :
Java 7
1. Here
TreeMap shouldn’t allow NULL keys at any situation. If we are trying to insert
the NULL keys we will get NullPointerException.
Example :
Output :
Reason :
·
In Java 7 The TreeMap class put method having
the following line
- compare(key, key); // type (and possibly null) check
The above line
is used to check the NULL and Type of Keys, But this line is not available in
Java 6 TreeMap Class.
No comments:
Post a Comment