当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。