简体   繁体   中英

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM