如何将String对象转换为Boolean对象?

367

如何将 String 对象转换为 Boolean 对象?


3
字符串的价值是什么? - James Goodwin
3
你对将字符串转换为布尔值的期望是什么? - Steve Kuo
1
我的变量类型布尔值 = !!要转换的值 - user2818054
16个回答

586

尝试以下方法(根据您所需的结果类型):

Boolean boolean1 = Boolean.valueOf("true");
boolean boolean2 = Boolean.parseBoolean("true");

优点:

  • Boolean类型:它不会创建新的Boolean实例,因此性能更好(垃圾回收也更少)。它会重用两个实例中的一个,即Boolean.TRUEBoolean.FALSE
  • boolean类型:不需要实例,你可以使用原始类型。

官方文档在Javadoc中。


更新:

虽然自动装箱也可以使用,但是这有一定的性能成本。
我建议只在必须自己进行转换时才使用它,而不是在避免转换时使用。


1
将 Boolean.valueOf 分配给 boolean2 不会自动取消装箱吗?我在这里看不出与 parseBoolean 的区别。 - Alex Feinman
14
最大的问题是当Boolean看到不应接受的内容时,它不会抛出异常。它将对其视为“true”并将返回true,对于其他所有内容都将返回false。如果您想强制将字符串匹配到适当的布尔值,则必须添加额外的逻辑以手动捕获非法情况。 - Brandon Belvin
1
如果我使用 boolean boolean2 = Boolean.valueOf("true"); 会怎样? - Vipin Verma
2
如果String对象为空,则Boolean.valueOf(String)将返回false。但是,Boolean也可以持有null值。您能提供任何帮助吗? - amit kate
因为这是最佳答案,您能否更新它以警告人们不要使用这些危险的方法?(很遗憾,我不知道常见库中是否有任何良好的实现。) - ddekany

105

当你使用 Boolean.valueOf(string)Boolean.parseBoolean(string) 时,必须小心。其原因是,如果字符串不等于“true”(忽略大小写),这些方法将始终返回false。

例如:

Boolean.valueOf("YES") -> false

因为这种行为,我建议添加一些机制来确保应翻译为布尔值的字符串遵循指定的格式。

例如:

if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
    Boolean.valueOf(string)
    // do something   
} else {
    // throw some exception
}

11
这是我见过的最好的例子,也应该在布尔类型中一开始就实现。对于许多应用程序来说,为无效的布尔值抛出异常非常重要。 - Brandon Belvin
2
不,那并非完全正确。 以下是 parseBoolean 的基础实现: public static boolean parseBoolean(String s) { return ((s != null) && s.equalsIgnoreCase("true")); } - electricalbah
1
呵呵...如果你需要编写这样的代码,那么你就不需要调用Boolean.valueOf。相反,你可以简单地重构这个if语句,使它做你想要的事情;-) - user2266462

23
Boolean b = Boolean.valueOf(string);

如果字符串不为空且等于true(忽略大小写),则b的值为true。


20
除了KLE的出色答案之外,我们还可以做得更加灵活:
boolean b = string.equalsIgnoreCase("true") || string.equalsIgnoreCase("t") || 
        string.equalsIgnoreCase("yes") || string.equalsIgnoreCase("y") || 
        string.equalsIgnoreCase("sure") || string.equalsIgnoreCase("aye") || 
        string.equalsIgnoreCase("oui") || string.equalsIgnoreCase("vrai");

(灵感来自zlajo的回答... :-))

1
-1和0怎么办呢?;o) - Minty

11
boolean b = string.equalsIgnoreCase("true");

11

现在,2018年1月份最好的方法是使用apache的BooleanUtils.toBoolean,这将把任何类似布尔值的字符串转换为布尔值,例如 Y、yes、true、N、no、false等。非常方便!


7
使用 Apache Commons 库中的 BooleanUtils 类:
String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
    System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}

结果:

Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false

BooleanUtils是什么? - james.garriss
2
org.apache.commons.lang3.BooleanUtils 是来自 Apache commons Lang API。 - Dhana
感谢您的努力收集所有使用案例。 - Gaurav
1
注意,BooleanUtils 仍然存在问题(虽然比 Boolean 方法少一些),因为如果值既不被识别为 true 也不被识别为 false,它将不会抛出异常。因此,ture(某人在某处的拼写错误)仍然被盲目地认为是 false。我在 Guava 中也找不到任何东西(例如在 23.0 版本中没有 Booleans.stringConverter)。 - ddekany
你不能处理每一个打字错误 - 那是一个完全不同的问题。 - ryanwebjackson
你不能处理每一个打字错误——那是一个完全不同的问题。 - undefined

6
public static boolean stringToBool(String s) {
        s = s.toLowerCase();
        Set<String> trueSet = new HashSet<String>(Arrays.asList("1", "true", "yes"));
        Set<String> falseSet = new HashSet<String>(Arrays.asList("0", "false", "no"));

        if (trueSet.contains(s))
            return true;
        if (falseSet.contains(s))
            return false;

        throw new IllegalArgumentException(s + " is not a boolean.");
    }

将字符串转换为布尔值的方法。


1
这也是我的首选方法,稍作修改。+1 - Cardinal System

1
这是我的做法:

"1##true".contains( string )

对于我的情况,大多数情况下要么是1,要么是true。我使用哈希作为分隔符。

0

如果你只是想将这个字符串变量与“false”或“true”字符串进行比较,而不是硬编码这两个值,就像我的情况一样,并且你不想使用Boolean.valueOf(),因为它会将任何被视为“true”的东西返回为true,并将其他所有东西返回为false,正如Brandon指出的那样,你可以采取以下措施。

if (someStringVariable.equals(Boolean.TRUE.toString())) {
...
}

或类似的方式,

if (someStringVariable.equals(Boolean.FALSE.toString())) {
...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接