Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading