Byte构造函数和Byte.valueOf()方法之间的区别

raj*_*eev 3 java

Byte byte1=new Byte("10");
Byte byte2=Byte.valueOf("10");

System.out.println(byte1);
System.out.println(byte2);
Run Code Online (Sandbox Code Playgroud)

byte1和byte2都打印相同的值10.然后构造函数参数化的Byte和valueOf()方法之间的区别是什么.

Tof*_*eer 11

JDK 7中字节类的源代码显示了这一点:

(我选择了字节版本而不是String版本,因为代码较少,但想法完全相同)

public static Byte valueOf(byte b) 
{
    final int offset = 128;
    return ByteCache.cache[(int)b + offset];
}
Run Code Online (Sandbox Code Playgroud)

和:

public Byte(byte value) 
{
   this.value = value;
}
Run Code Online (Sandbox Code Playgroud)

ByteCache的位置是:

private static class ByteCache 
{
    private ByteCache(){}

    static final Byte cache[] = new Byte[-(-128) + 127 + 1];

    static 
    {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Byte((byte)(i - 128));
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上构造函数版本用于创建一个全新valueOf版本,版本返回一个预先存在的版本.这样可以节省内存,因为Byte.valueOf(10)无论您调用它的次数如何,只有一个值,但如果您这样做,new Byte(10)则会为每次调用创建一个新值new.由于字节是不可变的(它们没有可变状态),因此没有理由为任何给定值创建多个字节.


Ben*_*Ben 9

文档valueOf()方法解决了这个:

If a new Byte instance is not required, this method should generally be used in preference to the constructor Byte(byte), as this method is likely to yield significantly better space and time performance since all byte values are cached.