HashMap get(Object)总是返回String而不是其他Object
遇到一个困扰我的问题.我有一个HashMap声明为使用字符串作为键,并使用我自己的KWIKattribute作为值.
Having an issue that is just stumping me. I have a HashMap declared to use a String as the Key and my own KWIKattribute as the Value.
private HashMap<String, KWIKattribute> attributes = new HashMap<String, KWIKattribute>();
我将对象放入其中,其中sgml_xml_tag是字符串,而kattr是KWIKattribute的实例.
I put objects into it, where sgml_xml_tag is a String and kattr is an instance of KWIKattribute.
attributes.put(sgml_xml_tag, kattr);
当我尝试将其值作为KWIKattribute收回时
When I try to get the value back out as a KWIKattribute
for (Map.Entry<String, KWIKattribute> e : attributes.entrySet()) {
String key = e.getKey();
KWIKattribute kattr = (KWIKattribute) attributes.get(e.getKey());
}
引发异常
javax.faces.el.EvaluationException: java.lang.ClassCastException: java.lang.String cannot be cast to com.northgrum.adt.kwik.model.KWIKattribute
我知道这对我而言可能是一个简单的愚蠢错误,但我看不到它是什么.有什么建议吗?
I know this is probably a simple stupid error on my part somewhere, but I'm not seeing what it is. Any suggestions?
用于迭代Map条目集的 Map.Entry
类具有 getValue()
-方法,它将值返回到当前键.
The Map.Entry
-class, which you use to iterate over the entry-set of your Map has a getValue()
-method, which returns the value to the current key.
Otherwise, if you're only interested in the values from the Map, you can also iterate over the values-collection:
for (KWIKattribute attr : attributes.values()){
// Do your work with attr
}