Skip to content
Advertisement

How can I check if a hashmap contains a key of a custom class type?

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!");
}

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement