在java中将布尔对象转换为字符串的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18833054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:28:55  来源:igfitidea点击:

Best approach to converting Boolean object to string in java

javaboolean

提问by Rachel

I am trying to convert boolean to string type...

我正在尝试将布尔值转换为字符串类型...

Boolean b = true;
String str = String.valueOf(b);

or

或者

Boolean b = true;
String str = Boolean.toString(b);

which one of above would be more efficient?

以上哪一项会更有效?

采纳答案by Rohit Jain

I don't think there would be any significant performance difference between them, but I would prefer the 1st way.

我不认为它们之间会有任何显着的性能差异,但我更喜欢第一种方式。

If you have a Booleanreference, Boolean.toString(boolean)will throw NullPointerExceptionif your reference is null. As the reference is unboxed to booleanbefore being passed to the method.

如果你有一个Boolean参考,Boolean.toString(boolean)将抛出NullPointerException,如果你的参考是null。由于引用boolean在传递给方法之前被取消装箱。

While, String.valueOf()method as the source code shows, does the explicit nullcheck:

同时,String.valueOf()源代码显示的方法进行了显式null检查:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Just test this code:

只需测试此代码:

Boolean b = null;

System.out.println(String.valueOf(b));    // Prints null
System.out.println(Boolean.toString(b));  // Throws NPE


For primitive boolean, there is no difference.

对于原始布尔值,没有区别。

回答by Pshemo

If you are sure that your value is not nullyou can use third option which is

如果您确定您的价值不是,null您可以使用第三个选项

String str3 = b.toString();

and its code looks like

它的代码看起来像

public String toString() {
    return value ? "true" : "false";
}


If you want to be null-safe use String.valueOf(b)which code looks like

如果你想是空安全使用String.valueOf(b)代码看起来像

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

so as you see it will first test for nulland later invoke toString()method on your object.

如您所见,它将首先测试null并稍后调用toString()对象上的方法。



Calling Boolean.toString(b)will invoke

调用Boolean.toString(b)将调用

public static String toString(boolean b) {
    return b ? "true" : "false";
}

which is little slower than b.toString()since JVM needs to first unboxBooleanto booleanwhich will be passed as argument to Boolean.toString(...), while b.toString()reuses private boolean valuefield in Booleanobject which holds its state.

这是比慢一点b.toString(),因为JVM需要首先拆箱Booleanboolean其将作为参数传递Boolean.toString(...),而b.toString()重新使用private boolean value在该领域Boolean对象保持其状态。

回答by Rohit Jain

public class Sandbox {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Boolean b = true;
        boolean z = false;
        echo (b);
        echo (z);
        echo ("Value of b= " + b +"\nValue of z= " + z);
    }

    public static void echo(Object obj){
        System.out.println(obj);
    } 

}
Result
--------------
true
false
Value of b= true
Value of z= false
--------------
Result
--------------
true
false
Value of b= true
Value of z= false
--------------

回答by jskidd3

If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:

如果您正在寻找一种快速的方法来执行此操作,例如调试,您可以简单地将一个空字符串连接到布尔值上:

System.out.println(b+"");

However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.

但是,我强烈建议使用另一种方法进行生产。这是一个简单的快速解决方案,对调试很有用。

回答by Shashank

If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:

如果这是为了获得一个恒定的“真”值,而不是“真”或“真”,你可以使用这个:

Boolean.TRUE.toString();
Boolean.FALSE.toString();

回答by kmera

Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.

取决于你所说的“高效”是什么意思。在性能方面,两个版本都与其相同的字节码相同。

$ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
  public static java.lang.String valueOf(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #14                 // String true
       6: goto          11
       9: ldc           #10                 // String false
      11: areturn


$ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
  public static java.lang.String toString(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #3                  // String true
       6: goto          11
       9: ldc           #2                  // String false
      11: areturn

回答by singh30

If you see implementation of both the method, they look same.

如果您看到这两种方法的实现,它们看起来是一样的。

String.valueOf(b)

String.valueOf(b)

public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }

Boolean.toString(b)

Boolean.toString(b)

public static String toString(boolean b) {
        return b ? "true" : "false";
    }

So both the methods are equally efficient.

所以这两种方法的效率是一样的。