public
K higherKey(K key)
Returns
the least key strictly greater than the given key, or null if there
is no such key.
import java.util.*; class TreeMapHigherKey{ public static void main(String args[]){ TreeMap<Integer, String> myMap; Integer myKey; myMap = new TreeMap<> (); /* Add Elements to myMap */ myMap.put(2, "w"); myMap.put(4, "wx"); myMap.put(6, "wxy"); myMap.put(8, "wxyz"); myKey = myMap.higherKey(4); System.out.println("Elements in myMap are"); System.out.println(myMap); System.out.println("Higher key for the key 4 is "); System.out.println(myKey); myKey = myMap.higherKey(8); System.out.println("Higher key for the key 8 is "); System.out.println(myKey); } }
Output
Elements in myMap are {2=w, 4=wx, 6=wxy, 8=wxyz} Higher key for the key 4 is 6 Higher key for the key 8 is null
1. Throws
NullPointerException if the specified key is null and this map uses
natural ordering, or its comparator does not permit null keys
import java.util.*; class TreeMapHigherKeyNullPointer{ public static void main(String args[]){ TreeMap<Integer, String> myMap; Integer myKey; myMap = new TreeMap<> (); /* Add Elements to myMap */ myMap.put(2, "w"); myMap.put(4, "wx"); myMap.put(6, "wxy"); myMap.put(8, "wxyz"); System.out.println("Elements in myMap are"); System.out.println(myMap); System.out.println("Higher key for the key null is "); myKey = myMap.higherKey(null); } }
Output
Elements in myMap are {2=w, 4=wx, 6=wxy, 8=wxyz} Higher key for the key null is Exception in thread "main" java.lang.NullPointerException at java.util.TreeMap.compare(TreeMap.java:1290) at java.util.TreeMap.getHigherEntry(TreeMap.java:463) at java.util.TreeMap.higherKey(TreeMap.java:777) at TreeMapHigherKeyNullPointer.main(TreeMapHigherKeyNullPointer.java:20)
No comments:
Post a Comment