I have no idea why I can pass any type of value to the HashMap.containsKey() method. I assume this method is an instance method (correct me if I am wrong) of HashMap Class which should be constrained by generic typing. If JAVA doesn't want to constrain it , why does the HashMap.put() method need to match the type it is parameterized with ...
HashMap<String, String> map = new HashMap<String, String>();
// invalid
// map1.put(1, "a");
I can't put int
value key to my HashMap
map
having the key type of String
. What is different between both the containsKey() and put() methods ?
public static void main(String[] args) {
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("1", "a");
map1.put("2", "b");
map1.put("3", "c");
if (map1.containsKey(1)) {
System.out.println("contain");
}
else {
System.out.println("not contain");
}
}
In the above code,not contain
was output, and the compiler didn't object. If it did, It would prevent this mistake from happening! Am I right? If not, please guide me to the truth.
Thanks for reading my question!