Java中的 TreeMap floorKey() 示例
先决条件: Java中的 TreeMap
floorKey()方法用于从参数返回小于或等于给定键的最大键。
句法:
public K floorKey(K key)
参数:此方法接受一个强制参数键,这是要匹配的键。
返回值:方法调用返回小于或等于 key 的最大键,如果没有这样的键,则返回null 。
异常:此方法抛出以下异常:
- ClassCastException :当指定的键无法与 Map 中可用的键进行比较时。
- NullPointerException : 当 map 中的指定键为 null 并且它使用 natural
排序这意味着,比较器不允许空键。
下面举例说明 floorKey() 方法的使用:
示例 1:
// Java program to demonstrate floorKey() method
import java.util.TreeMap;
public class FloorKeyDemo {
public static void main(String args[])
{
// create an empty TreeMap
TreeMap numMap = new TreeMap();
// Insert the values
numMap.put(6, "Six");
numMap.put(1, "One");
numMap.put(5, "Five");
numMap.put(3, "Three");
numMap.put(8, "Eight");
numMap.put(10, "Ten");
// Print the Values of TreeMap
System.out.println("TreeMap: " + numMap.toString());
// Get the greatest key mapping of the Map
// As here 11 is not available it returns 10
// because ten is less than 11
System.out.print("Floor Entry of Element 11 is: ");
System.out.println(numMap.floorKey(11));
// This will give null
System.out.print("Floor Entry of Element 0 is: ");
System.out.println(numMap.floorKey(0));
}
}
输出:
TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Floor Entry of Element 11 is: 10
Floor Entry of Element 0 is: null
示例 2:演示 NullPointerException
// Java program to demonstrate floorKey() method
import java.util.TreeMap;
public class FloorKeyDemo {
public static void main(String args[])
{
// create an empty TreeMap
TreeMap
numMap = new TreeMap();
// Insert the values
numMap.put(6, "Six");
numMap.put(1, "One");
numMap.put(5, "Five");
numMap.put(3, "Three");
numMap.put(8, "Eight");
numMap.put(10, "Ten");
// Print the Values of TreeMap
System.out.println("TreeMap: " + numMap.toString());
try {
// Passing null as parameter to floorKey()
// This will throw exception
System.out.println(numMap.floorKey(null));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Exception: java.lang.NullPointerException