简体   繁体   中英

Java Map can't get boolean

I have a Map like this:

Map<String, Boolean> settings = new HashMap<String, Boolean>();

if I create a new boolean like this:

boolean bool = settings.get("something");

with or without (boolean) Gradle says:

Cannot cast java.lang.Object to java.lang.boolean

(Well, this Object is a boolean) If I try to do parseBoolean(String) Compiler works fine, but if I execute, I get:

Cannot cast java.lang.Boolean to java.lang.String

So, what should I do, i know that the first is right and works for other people.

Edit: A little fault, Gradle says:

Object cannot be converted to boolean

Which means pretty much the same.

The method get will return Boolean (Object) which is wrapper over boolean (primitive). Hence you may need to apply cast.

Depending on your situation, maybe you don't need to store a boolean at all? Would it be enough to use a HashSet and add Strings only if their value is 'true'?

Then you could write:

boolean bool = settings.contains("something");

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