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


Java TreeMap.containskey()、containsValue()用法及代码示例


Java.util.TreeMap中有contains()的两个变体,本文都将进行讨论。

1. containskey(Object o):如果映射包含指定键的映射,则返回true。

参数:
o:The key which will be tested whether present or not.
返回值:
Returns true if there is a mapping for the given key.
Exception:
ClassCastException:This is thrown if the given key cannot be compared
with the keys currently in the map.
NullPointerException:This is thrown if the specified key is null.

// Java code to demonstrate the working 
// of containsKey() 
  
import java.io.*; 
import java.util.*; 
  
public class containsKey { 
public static void main(String[] args) 
    { 
  
        // Declaring the tree map of Integer and String 
        TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); 
  
        // assigning the values in the tree map 
        // using put() 
        treemap.put(2, "two"); 
        treemap.put(7, "seven"); 
        treemap.put(3, "three"); 
        treemap.put(6, "six"); 
        treemap.put(9, "nine"); 
  
        // Use of containsKey 
        // returns true if mapping for the number is present 
        System.out.println(treemap.containsKey(6)); 
        System.out.println(treemap.containsKey(4)); 
    } 
}

输出:


true
false

2. containsValue(Object o):如果此映射将一个或多个键映射到指定值,则返回true。

参数:
o:This is the value whose presence in this map is to be tested.
返回值:
Returns true if a mapping to this value exists else false.
Exception:
NA

// Java code to demonstrate the working 
// of containsValue() 
  
import java.io.*; 
import java.util.*; 
  
public class containsValue { 
public static void main(String[] args) 
    { 
  
        // Declaring the tree map of Integer and String 
        TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); 
  
        // assigning the values in the tree map 
        // using put() 
        treemap.put(2, "two"); 
        treemap.put(7, "seven"); 
        treemap.put(3, "three"); 
        treemap.put(6, "six"); 
        treemap.put(9, "nine"); 
  
        // Use of containsValue 
        // returns true if more than one keys are mapped 
        System.out.println(treemap.containsValue("six")); 
        System.out.println(treemap.containsValue("four")); 
    } 
}

输出:

true
false


相关用法


注:本文由纯净天空筛选整理自 Java.util.TreeMap.containskey() and containsValue() in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。