简体   繁体   中英

HashMap ClassCastException String to MyClass

I want to iterate over a 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"

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. It seems as if the object is in fact a String as I get this Exception:

java.lang.ClassCastException: java.lang.String cannot be cast to MyClass

I don't get it. I pass the HashMap several times and the SettingsClass casts the stored object to the HashMap without problems. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM