TreeMap put(K, V) in Java

put(K, V): This method is available in java.util.TreeMap class of Java.

Syntax:

String java.util.TreeMap.put(K key, V value)

This method takes two arguments. This method associates the specified value with the specified key in this map.

Note: If the map previously contained a mapping for the key, the oldvalue is replaced.

Parameters: Two parameters are required for this method.

key: key with which the specified value is to be associated.

value: value to be associated with the specified key.

Returns: the previous value associated with the key, or null if there was no mapping for the key.

Throws:

1. ClassCastException - if the specified key cannot be compared with the keys currently on the map.

2. NullPointerException - if the specified key is  null and this map uses natural ordering, or its comparator does not permit null keys

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapput {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        Integer key = 10;

        String value = "World";
        treeMap.put(key, value);
        System.out.println(treeMap);

    }
}

Output:

{10=World}


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMapput {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        Integer key = null;

        String value = "World";
        treeMap.put(key, value);
        System.out.println(treeMap);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:768) at java.base/java.util.TreeMap.put(TreeMap.java:777) at java.base/java.util.TreeMap.put(TreeMap.java:534)


No comments:

Post a Comment