简体   繁体   中英

Cast exception issue in map with values of type Object

Follow the code block.

Map<String, Object> personDetailMap = new HashMap<String, Object>();
personDetailMap.put("name", "isuru");
personDetailMap.put("is-male", true);
(String)personDetailMap.get("is-male");

Final statement causes an exception: ClassCastException cannot cast Boolean to String also note that value I'm trying to read is put as of primitive type boolean

My question is personDetailMap will return a object of Class Object then why its giving a cast exception of Boolean to String.

personDetailMap.put("is-male", true); stores a Boolean by boxing the primitive boolean into an object. personDetailMap.get("is-male"); returns that same Boolean .

Then you try to cast the Boolean to a String although those 2 classes have no relationship. The cast fails and you get that exception.

The statement (String) anObject; can only work if anObject is a String (String being final, there aren't any sub classes).

If you actually want to convert the boolean into a string, you can use the following method:

String boolStr = personDetailMap.get("is-male").toString(); // boolStr = "true"

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