You are casting an Object to a Boolean, and that object is instance of java.lang.String
.
It means that you in some place put
watcherMap.put(someInteger,"SomeString");
getBoolean(someInteger);
And this will throw a ClassCastException
题
I've got a HashMap<Integer, Object>
and I've got a getter function for it as such:
public Boolean getBoolean(int index){
return (boolean) watcherMap.get(index);
}
When calling this class, I get this error
Exception in thread "Thread-0" java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Boolean
at com.vobis.onebullet.entity.DataWatcher.getBoolean(DataWatcher.java:36)
at com.vobis.onebullet.entity.Entity.updateLocally(Entity.java:91)
at com.vobis.onebullet.level.Level.updateLevel(Level.java:149)
at com.vobis.onebullet.OneBullet.loop(OneBullet.java:264)
at com.vobis.onebullet.OneBullet.start(OneBullet.java:228)
at com.vobis.onebullet.OneBullet.run(OneBullet.java:125)
at java.lang.Thread.run(Unknown Source)
But no where in that function am I casting a String to a boolean? I'm casting a boolean to an object!
解决方案
You are casting an Object to a Boolean, and that object is instance of java.lang.String
.
It means that you in some place put
watcherMap.put(someInteger,"SomeString");
getBoolean(someInteger);
And this will throw a ClassCastException
其他提示
There wont be any error if you keep
watcherMap.put(1, true);
or something like
watcherMap.put(2, Boolean.FALSE)
But definitely an issue if you say
watcherMap.put(1, "true");
Can you show us what are you putting to watcherMap?
Seems like Hashmap is storing (Integer,String) in the situation where it threw this exception. Please remember Object is the parent class of classes in Java and hence it's reference can hold any object.