简体   繁体   English

Java Map 无法获得布尔值

[英]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:有或没有(布尔值)Gradle 说:

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: (嗯,这个对象是一个布尔值)如果我尝试做 parseBoolean(String) 编译器工作正常,但如果我执行,我得到:

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:编辑:有点错误,Gradle 说:

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).方法get将返回Boolean (对象),它是boolean (原始值)的包装器。 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'?仅当字符串的值为“true”时才使用 HashSet 并添加字符串就足够了吗?

Then you could write:然后你可以写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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