[英]HashMap ClassCastException String to MyClass
I want to iterate over a HashMap. 我想遍历HashMap。
public void setMyHashMap(final String key,
final HashMap<Integer, MyClass> value) throws NullPointerException{
settings.put(key, value);
}
public HashMap<Integer, MyClass> getMyHashMap(String key) {
return (HashMap<Integer, MyClass>) settings.get(key);
}
------------------------------------------------------------
for (Map.Entry<Integer, MyClass> e : settings.getMyHashMap(key)
.entrySet()) {
System.out.println(e.getValue());
}
This displays a reference to an object of MyClass like "MyClass@9d5f8e" 这将显示对MyClass对象的引用,例如“ MyClass @ 9d5f8e”
for (Map.Entry<Integer, MyClass> e : settings.getMyHashMap()
.entrySet()) {
System.out.println(e.getValue().getLabel());
}
But as soon as I want to access data of this object, it gets casted to MyClass, which should be ok but isn't. 但是,只要我要访问该对象的数据,它就会被强制转换为MyClass,这应该可以,但不能。 It seems as if the object is in fact a String as I get this Exception:
当我收到此异常时,似乎该对象实际上是一个String:
java.lang.ClassCastException: java.lang.String cannot be cast to MyClass java.lang.ClassCastException:无法将java.lang.String强制转换为MyClass
I don't get it. 我不明白 I pass the HashMap several times and the SettingsClass casts the stored object to the HashMap without problems.
我多次传递了HashMap,SettingsClass将存储的对象强制转换为HashMap,没有问题。 If I print the value I get the reference to MyClass but as soon as I want to access data in it, the JRE thinks it's a String object.
如果我打印该值,则会获得对MyClass的引用,但是一旦我要访问其中的数据,JRE就会认为这是一个String对象。
Your code should work - I just tried it out: 您的代码应该可以工作-我刚刚尝试了一下:
class MyClass {
public String foo;
public String bar;
public String getLabel() {
return "foo: " + foo + ", bar: " + bar;
}
}
MyClass myObj1 = new MyClass();
myObj1.foo = "foo1";
myObj1.bar = "bar1";
MyClass myObj2 = new MyClass();
myObj2.foo = "foo2";
myObj2.bar = "bar2";
java.util.Map<Integer, MyClass> myHashMap = new java.util.HashMap<Integer, MyClass>();
myHashMap.put(1, myObj1);
myHashMap.put(2, myObj2);
for (java.util.Map.Entry<Integer, MyClass> e : myHashMap.entrySet()) {
System.out.println(e.getValue().getLabel());
}
This produced the output (as expected): 这产生了输出(如预期的那样):
foo: foo1, bar: bar1
foo: foo2, bar: bar2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.