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


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


描述

這個containsKey(Object key)如果此映射包含指定鍵的映射,則使用方法返回 'true'。

聲明

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

public boolean containsKey(Object key)

參數

key- 這是要測試其在此Map中是否存在的 key 。

返回值

如果此映射包含指定鍵的映射,則方法調用返回 true。

異常

  • ClassCastException- 如果無法將指定的鍵與Map中當前的鍵進行比較,則會拋出此問題。

  • NullPointerException- 如果指定的鍵為空並且此映射使用自然排序,或者其比較器不允許空鍵,則拋出此問題。

示例

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

package com.tutorialspoint;

import java.util.*;

public class TreeMapDemo {
   public static void main(String[] args) {
      
      // creating tree map 
      NavigableMap<Integer, String> treemap = 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");

      System.out.println("Checking key value 6");
      System.out.println("Value for key 6 exists:"+ treemap.containsKey(6));
   }    
}

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

Checking key value 6
Value for key 6 exists:true

相關用法


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