differences between ContainsKey and get methods in map
The Map collection allows the value object to be null and has no number limits, so when the return value of the Get () method is null, there may be two cases where the key object is not in the collection, and the other is that the key object does not map any value objects, that is, the value object is null. Therefore, you should not use the Get () method to determine whether a key exists in the map collection, but instead use the ContainsKey () method to determine it, such as the following example.
The following code first creates a map collection that is implemented by the HashMap class, and sequentially adds a map of the value object to the map collection as null and Mr. Ma, and then executes the two key objects through the Get () and ContainsKey () methods, and executes a nonexistent key object. The key code is as follows:
Testcollection.java Key Code:
public static void Main (string[] args) {
Map<integer, string> map = new Hashmap<integer, string> ();
Map.put (220180, NULL);
Map.put (220181, "Mr. Ma");
System.out.println ("The return result of the Get () method:");
System.out.print ("------" + map.get (220180));
System.out.print ("" + Map.get (220181));
System.out.println ("" + Map.get (220182));
System.out.println ("The return result of the ContainsKey () method:");
System.out.print ("------" + Map.containskey (220180));
System.out.print ("" + Map.containskey (220181));
System.out.println ("" + Map.containskey (220182));
}
Testcollection.java Complete code:
Package com.mwq;
Import Java.util.HashMap;
Import Java.util.Map;
public class Testcollection {
public static void Main (string[] args) {
System.out.println ("Start:");
Map<integer, string> map = new Hashmap<integer, string> ();
Map.put (220180, NULL);
Map.put (220181, "Mr. Ma");
System.out.println ("The return result of the Get () method:");
System.out.print ("------" + map.get (220180));
System.out.print ("" + Map.get (220181));
System.out.println ("" + Map.get (220182));
System.out.println ("The return result of the ContainsKey () method:");
System.out.print ("------" + Map.containskey (220180));
System.out.print ("" + Map.containskey (220181));
System.out.println ("" + Map.containskey (220182));
System.out.println ("End.") ");
}
}
To execute the above code, the following information will be output from the console:
The return result of the Get () method:
------NULL Mr. MA NULL
The return result of the ContainsKey () method:
------True False
Summary: Determine if there is a key in the Map collectionContainsKey method, take the value of the key with the Get method.