I decided to read the JDK source somehow. That said, I don't have time to read each line carefully, so I read it briefly and found this code.
The Byte class is a wrapper class for the primitive type byte. It seems that I haven't found anything by reading the source, which is surprising.
First, the fields and the constructor. Well, it's a source that everyone can imagine.
Byte.java
private final byte value;
public Byte(byte value) {
this.value = value;
}
Actually, there is a ByteCache class that cannot be seen in javadoc.
Byte.java
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));
}
}
What we're doing is caching instances from -128 to 127. Oh, it means that all byte values are in the cache.
It is a cache of ByteCache, but it is referenced by valueOf.
Byte.java
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
If the instance is in the cache, you can compare it with the == operator. Try out.
Main.java
public static void main(String[] args) {
byte b0 = 1;
Byte b1 = new Byte(b0);
Byte b2 = Byte.valueOf(b0);
Byte b3 = b0;
System.out.println(b1 == b2);
System.out.println(b1 == b3);
System.out.println(b2 == b3);
}
Result is···
false
false
true
That's too bad. It is natural that new Byte () will create another instance, but the reference value of the instance will be different. However, the fact that autoboxing (variable b3) is the same as Byte.valueOf () means that autoboxing calls Byte.valueOf () instead of new Byte ().
Well, not really. Speaking of force, the compiler gets angry that the int type cannot be converted to the byte type when writing new Byte (1) or Byte.valueOf (1), but you can see that the constant does not exceed the range of bytes! I feel like. The compiler seems to be smart and quite stubborn, so I want it to be a little more flexible.
Recommended Posts