📜  Java.util.TreeMap.containskey() 和 containsValue() 在Java

📅  最后修改于: 2022-05-13 01:55:06.742000             🧑  作者: Mango

Java.util.TreeMap.containskey() 和 containsValue() 在Java

Java.util.TreeMap 中的 contains() 有两种变体,本文将讨论这两种变体。

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

Parameters:
o : The key which will be tested whether present or not.
Return Value:
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 treemap = new TreeMap();
  
        // 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。

Parameters:
o : This is the value whose presence in this map is to be tested.
Return Value:
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 treemap = new TreeMap();
  
        // 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