HashMap get(Object)总是返回String而不是其他Object [英] HashMap get(Object) always returns String instead of other Object

查看:69
本文介绍了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.

否则,如果您仅对Map中的值感兴趣,则还可以遍历

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
}

这篇关于HashMap get(Object)总是返回String而不是其他Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆