目录

NavigableMap<K,V> headMap(K toKey, boolean inclusive)

描述 (Description)

headMap(K toKey,boolean inclusive)方法用于返回此映射的部分视图,其键小于(或等于,如果包含为真)toKey。

声明 (Declaration)

以下是java.util.TreeMap.headMap()方法的声明。

public NavigableMap<K,V> headMap(K toKey,boolean inclusive)

参数 (Parameters)

  • toKey - 这是返回映射中键的高端点。

  • inclusive - 如果要将高端点包含在返回的视图中,则为true。

返回值 (Return Value)

方法调用返回此映射部分的视图,其键小于(或等于,如果包含为真)toKey。

异常 (Exception)

  • ClassCastException - 如果toKey与此映射的比较器不兼容,则抛出此异常。

  • NullPointerException - 如果toKey为null并且此映射使用自然排序,或者其比较器不允许空键,则抛出此异常。

  • IllegalArgumentException - 如果此映射本身具有受限范围,并且toKey位于范围的边界之外,则抛出此异常。

例子 (Example)

以下示例显示了java.util.TreeMap.headMap()方法的用法。

package com.iowiki;
import java.util.*;
public class TreeMapDemo {
   public static void main(String[] args) {
      // creating maps 
      TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
      NavigableMap<Integer, String> treemapheadincl = new TreeMap<Integer, String>();
      // populating tree map
      treemap.put(2, "two");
      treemap.put(1, "one");
      treemap.put(3, "three");
      treemap.put(6, "six");
      treemap.put(5, "five");
      // getting head map inclusive 3
      treemapheadincl = treemap.headMap(3,true);
      System.out.println("Checking values of the map");
      System.out.println("Value is: "+ treemapheadincl);
   }    
}

让我们编译并运行上面的程序,这将产生以下结果。

Checking values of the map
Value is: {1=one, 2=two, 3=three}
↑回到顶部↑
WIKI教程 @2018