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

本文翻译自:How to convert String object to Boolean Object?

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


#1楼

参考:https://stackoom.com/question/6SId/如何将String对象转换为Boolean对象


#2楼

Try (depending on what result type you want): 尝试(取决于您想要的结果类型):

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

Advantage: 优点:

  • Boolean: this does not create new instances of Boolean, so performance is better (and less garbage-collection). Boolean:这不会创建Boolean的新实例,因此性能更好(并且垃圾收集更少)。 It reuses the two instances of either Boolean.TRUE or Boolean.FALSE . 它重用了Boolean.TRUEBoolean.FALSE这两个实例。
  • boolean: no instance is needed, you use the primitive type. boolean:不需要实例,使用基本类型。

The official documentation is in the Javadoc . 官方文档在Javadoc中


UPDATED: 更新:

Autoboxing could also be used, but it has a performance cost. 也可以使用自动装箱,但它具有性能成本。
I suggest to use it only when you would have to cast yourself, not when the cast is avoidable. 我建议只在你必须施展自己的时候使用它,而不是在施放是可以避免的时候。


#3楼

Boolean b = Boolean.valueOf(string);

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


#4楼

You have to be carefull when using Boolean.valueOf(string) or Boolean.parseBoolean(string) . 使用Boolean.valueOf(string)Boolean.parseBoolean(string)时必须小心。 The reason for this is that the methods will always return false if the String is not equal to "true" (the case is ignored). 原因是如果String不等于“true”,则方法将始终返回false(忽略大小写)。

For example: 例如:

Boolean.valueOf("YES") -> false

Because of that behaviour I would recommend to add some mechanism to ensure that the string which should be translated to a Boolean follows a specified format. 由于这种行为,我建议添加一些机制,以确保应转换为布尔值的字符串遵循指定的格式。

For instance: 例如:

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

#5楼

Beside the excellent answer of KLE, we can also make something more flexible: 除了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");

(inspired by zlajo's answer... :-)) (灵感来自zlajo的回答...... :-))


#6楼

boolean b = string.equalsIgnoreCase("true");
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值