當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java TreeMap floorKey()用法及代碼示例


前提條件: Java中的TreeMap

floorKey()方法用於從參數中返回小於或等於給定鍵的最大鍵。

用法:


public K floorKey(K key)

參數:此方法接受必需的參數 key ,它是要匹配的 key 。

返回值:方法調用返回小於或等於key的最大鍵;如果沒有這樣的鍵,則返回null。

異常:此方法引發以下異常:

  • ClassCastException:當指定的 key 無法與Map中可用的 key 進行比較時。
  • NullPointerException :當map中指定的鍵為null且使用自然鍵時
    排序意味著比較器不允許使用空鍵。

下麵的示例說明了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<Integer, String> numMap = new TreeMap<Integer, String>(); 
  
        // 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<Integer, String> 
            numMap = new TreeMap<Integer, String>(); 
  
        // 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


相關用法


注:本文由純淨天空篩選整理自bilal-hungund大神的英文原創作品 TreeMap floorKey() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。