I have a hashmap whose keys are of a custom class type (class A) and I want to check whether an child class B (B extends A) appears as a key in the map.
IntelliJ gives me no warnings for the following code, but it's not going into the statement. What could be wrong?
HashMap<A, Integer> map = new HashMap<A, Integer>();
map.put(new B(), 1);
if (map.containsKey(new B())) {
System.out.println("Success!");
}
CodePudding user response:
You are checking if the Map contains a key of a specific instance of class B (not the class itself).
If you need to check if the Map contains a key of class B you can do:
boolean hasClass = map.keySet().stream().anyMatch(B.class::isInstance);
CodePudding user response:
You are creating a new instance of the B() object and that new instance is not in the HashMap. Try changing the code to
HashMap<A, Integer> map = new HashMap<A, Integer>();
B keyToBeTested = new B();
map.put(keyToBeTested, 1);
if (map.containsKey(keyToBeTested) {
System.out.println("Success!");
}
