Java中的lowerKey()示例

先决条件: Java中的树映射

null

这个 洛尔基() 方法用于返回严格小于给定键的最大键,并将其作为参数传递。简单地说,该方法用于查找作为参数传递的元素之后的下一个最大元素。

语法:

public K TreeMap.lowerKey(K key)

参数: 此方法采用强制参数 钥匙 这是匹配的关键。

返回值: 此方法返回 最伟大的钥匙严格来说比钥匙少, 无效的 如果没有这样的钥匙。

例外情况: 此方法引发以下异常:

  • 类别例外 :当指定的密钥无法与地图中的可用密钥进行比较时。
  • 空指针异常 :当映射中指定的键为空且使用自然 排序意味着,比较器不允许空键。

下面是使用lowerKey()方法的示例:

例1:

// Java program to demonstrate lowerKey() 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 9 is not available it returns 8
// because 9 is strictly less than 11, present
System.out.print( "Lower Key Entry of Element 9 is: " );
System.out.println(numMap.lowerKey( 9 ));
// Though, 3 is available in the Map
// it returns 1 because this method returns
// strictly less than key according to the specified key
System.out.print( "Lower Key Entry of Element 3 is: " );
System.out.println(numMap.lowerKey( 3 ));
}
}


输出:

TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Lower Key Entry of Element 9 is: 8
Lower Key Entry of Element 3 is: 1

例2: 演示NullPointerException

// Java program to demonstrate lowerKey() 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 lowerKey()
// This will throw exception
System.out.println(numMap.lowerKey( 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

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享