NavigableMap接口的higherKey()方法用於返回嚴格大於給定鍵的最小鍵;如果沒有這樣的鍵,則返回null。
用法:
public K higherKey(K key)
參數:該方法將 key k作為參數。
返回值:此方法返回大於key的最小鍵;如果沒有這樣的鍵,則返回null。
異常:如果指定鍵為null且此映射使用自然順序,或者其比較器不允許使用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");
// Pritnig 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");
// Printnig 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
相關用法
- Java TreeMap higherKey()用法及代碼示例
- Java NavigableMap put()用法及代碼示例
- Java NavigableMap lastEntry()用法及代碼示例
- Java NavigableMap floorEntry()用法及代碼示例
- Java NavigableMap floorKey()用法及代碼示例
- Java NavigableMap clear()用法及代碼示例
- Java NavigableMap lowerKey()用法及代碼示例
- Java NavigableMap size()用法及代碼示例
- Java NavigableMap isEmpty()用法及代碼示例
- Java NavigableMap higherEntry()用法及代碼示例
- Java NavigableMap pollLastEntry()用法及代碼示例
- Java NavigableMap ceilingEntry()用法及代碼示例
- Java NavigableMap ceilingKey()用法及代碼示例
- Java NavigableMap firstEntry()用法及代碼示例
- Java NavigableMap pollFirstEntry()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 NavigableMap higherKey() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。