![](/img/trans.png)
[英]How can I iterate a hashmap which contains a dto class as the value for the key?
[英]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 沒有給我以下代碼的警告,但它沒有進入語句。 有什么問題?
HashMap<A, Integer> map = new HashMap<A, Integer>();
map.put(new B(), 1);
if (map.containsKey(new B())) {
System.out.println("Success!");
}
您正在檢查Map
包含 class B
的特定實例的key
(不是 class 本身)。
如果您需要檢查Map
包含 class B
的密鑰,您可以執行以下操作:
boolean hasClass = map.keySet().stream().anyMatch(B.class::isInstance);
您正在創建 B() object 的新實例,並且該新實例不在 HashMap 中。 嘗試將代碼更改為
HashMap<A, Integer> map = new HashMap<A, Integer>();
B keyToBeTested = new B();
map.put(keyToBeTested, 1);
if (map.containsKey(keyToBeTested) {
System.out.println("Success!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.