本文翻译自: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
orBoolean.FALSE
. 它重用了Boolean.TRUE
或Boolean.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");