Java NavigableMap higherKey()方法

Java NavigableMap higherKey()方法

NavigableMap接口的 higherKey() 方法用于返回严格大于给定键的最小键,如果没有这样的键,则返回空。

语法

public K higherKey(K key)

参数: 该方法接受 键k 作为参数。

返回值: 该方法返回 大于key的最小key, 如果没有这样的key,则返回 null

异常: 如果指定的键是空的,而这个地图使用自然排序,或者它的比较器不允许空键,这个方法会抛出 NullPointerException

下面是一些例子来说明higherKey()方法。

例1 :

// Java program to demonstrate
// higherKey() method
// for <Integer, String>
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] args) throws Exception
    {
        try {
 
            // Creating object of NavigableMap
            NavigableMap<Integer, String>
                navmap = new TreeMap<Integer, String>();
 
            // Populating the map
            navmap.put(1, "One");
            navmap.put(2, "Two");
            navmap.put(3, "Three");
            navmap.put(4, "Four");
            navmap.put(5, "Five");
 
            // Printing the TreeMap
            System.out.println("NavigableMap: " + navmap);
 
            // Getting higher key value for 3
            // using higherKey() method
            int value = navmap.higherKey(3);
 
            // Printing the value
            System.out.println("The higherKey value "
                               + " for 3: " + value);
        }
 
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出

NavigableMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
The higherKey value  for 3: 4

例2: 对于NullPointerException

// Java program to demonstrate
// higherKey() method
// for NullPointerException
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] args) throws Exception
    {
        try {
 
            // Creating object of TreeMap<Integer, String>
            NavigableMap<Integer, String>
                navmap = new TreeMap<Integer, String>();
 
            // Populating tree map
            navmap.put(1, "One");
            navmap.put(2, "Two");
            navmap.put(3, "Three");
            navmap.put(4, "Four");
            navmap.put(5, "Five");
 
            // Printing the NavigableMap
            System.out.println("TreeMap: " + navmap);
 
            // Getting higher key value for null
            // Using higherKey() method
            System.out.println("Trying to get higherKey"
                               + " value for null");
 
            int value = navmap.higherKey(null);
 
            // Printing the value
            System.out.println("Value is: " + value);
        }
 
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出

TreeMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Trying to get higherKey value for null
Exception thrown : java.lang.NullPointerException

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程