0

I have some strange bug on Android 2.3 and lower.

I have following code:

HashMap<Somekey, Object> data = new HashMap<Somekey, Object>();
data.put(somekey, "asdfdsafdsf");
String value = (String) data.get(somekey);

on the last line I have ClassCastException: get(somekey) returns Boolean value instead of String. This error appears not only with String type, with Integer and Double too.

I don't understand why, because this code correctly works on android 4.0.3 and higher.

0

3 Answers 3

1

Well even if your code was running (???) your code is wrong and you should fix it. Maybe by checking the type with instanceof before casting.

You could do it the dirty way also:

String value = data.get(somekey).toString();
Sign up to request clarification or add additional context in comments.

Comments

1

So you did not put any boolean/Boolean into the map? Because Somekey might have a wrong hashCode() implementation, maybe all the same code, and the earlier HashMap implementations might have been buggy.

Purely the above code, without any Boolean, could not deliver that error.

Comments

1

I have tried your code and it works :

Somekey somekey = new Somekey();
HashMap<Somekey, Object> data = new HashMap<Somekey, Object>();
data.put(somekey, "asdfdsafdsf");
String value = (String) data.get(somekey);

May be you are not creating a java.util.HashMap but a custom and buggy implementation, for example :

public class HashMap<K, V> extends java.util.HashMap<K, V> {
    @Override
    public V get(Object key) {
        return (V)(Object)true;
    }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.