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


Java java.util.TreeMap.headMap()用法及代碼示例


描述

這個headMap(K toKey)方法用於返回此映射中鍵嚴格小於 toKey 的部分的視圖。

聲明

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

public SortedMap<K,V> headMap(K toKey)

參數

toKey- 這是返回映射中鍵的高端(不包括)。

返回值

方法調用返回此映射部分的視圖,其鍵嚴格小於 toKey。

異常

  • ClassCastException- 如果 toKey 與此映射的比較器不兼容(或者,如果映射沒有比較器,如果 toKey 未實現 Comparable),則拋出此異常。如果無法將 toKey 與映射中當前的鍵進行比較,則實現可以但不要求拋出此異常。

  • NullPointerException- 如果 toKey 為空並且此映射使用自然排序,或者其比較器不允許空鍵,則會引發此異常。

  • IllegalArgumentException- 如果此Map本身具有受限範圍,並且 toKey 位於範圍邊界之外,則會引發此異常。

示例

下麵的例子展示了 java.util.TreeMap.headMap() 方法的用法。

package com.tutorialspoint;

import java.util.*;

public class TreeMapDemo {
   public static void main(String[] args) {

      // creating maps 
      TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
      SortedMap<Integer, String> treemaphead = 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
      treemaphead = treemap.headMap(3);

      System.out.println("Checking values of the sorted map");
      System.out.println("Value is:"+ treemaphead);
   }    
}

讓我們編譯並運行上麵的程序,這將產生以下結果。

Checking values of the sorted map
Value is:{1=one, 2=two}

相關用法


注:本文由純淨天空篩選整理自 java.util.TreeMap.headMap() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。