我有以下类型的枚举。
enum plant{
rose("r"),lotus("l");
String label;
private plant(String label)
{
this.label = label;
}
}
代码:
HashMap hashMap = new HashMap();
hashMap.put(plant.rose.label,4);
Object object = hashMap;
HashMap<plant, Integer> a = (HashMap<plant, Integer>) object;
System.out.println(a.keySet().contains(plant.rose));
System.out.println(a);
输出:
false
{r=4}
为什么它没有给出任何
ClassCastException
对于 HashMap<plant, Integer> a = (HashMap<plant, Integer>) object;
也不
true
对于 a.keySet().contains(plant.rose)
?
最佳答案
泛型一旦编译,就会删除它们的类型参数,因此类型转换是将 Hashmap 的对象转换为 Hashmap,不存在运行时错误。
至于比较,您将标签作为哈希键,但将其与实际枚举进行比较,因此它不会相等。
关于java - 将对象类型转换为枚举不会给出枚举或错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27667025/