字节或字节,请说明

byte or Byte, please explain

我正在 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);

有什么区别?

不同之处在于 new String(byte[]) 情况下有合适的构造函数重载,而 new String(Byte) 情况下则没有。

这是为什么?

  • 因为它就是这样设计的。
  • 因为构造器的设计目的。
  • 因为 Java 设计者认为通常来说,用构造函数和方法重载来处理 API 来处理 很少 的变体并不是一个好主意用过。

您应该如何了解更多信息?例如,一个类型有哪些构造函数?他们做什么/是什么意思?

  • 通过阅读 javadoc!

顺便说一句,自动拆箱/加宽与这个例子无关。没有 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                                                                       
$   

这是因为自动装箱和拆箱的工作方式。您可以在这里获得更多信息:http://beginnersbook.com/2014/09/java-autoboxing-and-unboxing-with-examples/

嗯,最大的区别是,在一种情况下,您使用的是数组,而在另一种情况下,您不是。

但是,值得指出的是,即使在这两种情况下都使用数组,也会有所不同。即:

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[]是变量的类型,而第二个包含在 Java 中只是作为对习惯以这种方式编写东西的 C 程序员的让步。)

这里的重点是 Java 将自动装箱和自动拆箱 Bytebyte。也就是说,如果您有一个 Byte 变量并为其分配一个 byte,它将自动转换,反之亦然。然而,这种自动装箱和自动拆箱不适用于数组——Java 不会Byte[]byte[]之间自动转换。

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