有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java字节或字节,请解释

我正在JAVA中创建一个新的Byte对象,并使用Byte构造一个String对象,它给出了一个错误

Byte B1 = new Byte((byte)41);
String S1 = new String(B1);

但是,当我使用byte而不是Byte时没有问题

byte d[]= {65,48};
String s1 = new String(d);

有什么区别


共 (3) 个答案

  1. # 2 楼答案

    最大的区别是,在一种情况下,你使用的是数组,而在另一种情况下,你没有

    然而,值得指出的是,即使在这两种情况下都使用数组,也会有差异。也就是说:

    Byte[] d1 = {65,48};         // legal
    byte[] d2 = {65,48};         // legal
    String s1 = new String(d1);  // illegal
    String s2 = new String(d2);  // legal
    

    (注意:最好说Byte[] d1而不是Byte d1[];两者是等效的,但第一个变量明确指出Byte[]是变量的类型,而第二个变量仅作为对习惯于用这种方式编写东西的C程序员的让步而包含在Java中。)

    这里的要点是,Java将自动装箱和自动取消装箱Bytebyte。也就是说,如果你有一个Byte变量并给它赋值byte,它会自动转换,反之亦然。但是,这种自动装箱和自动取消装箱不适用于数组,Java不会在Byte[]byte[]之间自动转换

    不幸的是,我没有看到在这两种数组类型之间进行转换的简单方法,除非使用Apache Commons,它具有toObjecttoPrimitive数组转换(请参见here

  2. # 3 楼答案

    区别在于new String(byte[])情况下有一个合适的构造函数重载,而new String(Byte)情况下没有

    为什么

    • 因为它就是这样设计的
    • 因为构造器的设计目的
    • 因为Java设计人员认为,一般来说,用构造函数和方法重载来处理很少使用的变量,把API搞得乱七八糟是个坏主意

    你应该如何了解更多?例如,一个类型有什么构造函数?它们是什么意思

    • 通过阅读javadocs

    顺便说一下,自动拆箱/加宽与本例无关。没有String(byte)String(Byte)。。。或String(Object)构造函数。再多的拆箱或加宽也不能让这个例子起作用

    为了说明new String(...)不适用于byte

    public class Test {
        String s = new String((byte) 42);
    }
    $ javac Test.java 
    Test.java:2: error: no suitable constructor found for String(byte)
        String s = new String((byte) 42);
                   ^
        constructor String.String(String) is not applicable
          (argument mismatch; byte cannot be converted to String)
        constructor String.String(char[]) is not applicable
          (argument mismatch; byte cannot be converted to char[])
        constructor String.String(byte[]) is not applicable                                                                                                       
          (argument mismatch; byte cannot be converted to byte[])                                                                                                 
        constructor String.String(StringBuffer) is not applicable                                                                                                 
          (argument mismatch; byte cannot be converted to StringBuffer)                                                                                           
        constructor String.String(StringBuilder) is not applicable                                                                                                
          (argument mismatch; byte cannot be converted to StringBuilder)                                                                                          
    Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output                                                                   
    1 error                                                                       
    $