Skip to content
欢迎扫码关注公众号

JDK 17 源码阅读 - 数据类型 - 02 - Short

JDK 版本

以下代码均基于 JDK 17 版本。

ShortByte 类的定义基本一致,除了泛型的类型不一样:

java
@jdk.internal.ValueBased
public final class Short extends Number implements Comparable<Short>, Constable {
}

大部分的方法及实现也基本一致,这些部分就直接跳过,仅说一些有区别的地方。

首先要说的是 byteValue 方法:

java
public byte byteValue() { return (byte)value; }

由于 short 型使用 16 个 bit,数值范围比 byte 型大的多,强制转型时出现数据丢失,而且其转换过程有一些违反直觉。

看一下如下代码:

java
System.out.println(Short.valueOf((short) 255).byteValue()); // -1
System.out.println(Short.valueOf((short) 128).byteValue()); // -128

255 变成了 -1,而 128 却变成了 -128。

以 128 为例,由于其为正数,其反码和原码一致,为 0000 0000 1000 0000,其后 8 个 bit 正好是 byte 类型 -128 的反码。255 的反码为 0000 0000 1111 1111,其后 8 个 bit 是 -1 的反码。

也就是说强转的过程就是直接舍弃了高位的 8 bit,直接使用低位的 8 bit 作为其结果。其效果相当于 Byte.toUnsignedInt() 方法的反过程。

另一个要说的是 reverseBytes() 方法。其在 Byte 中没有对应的方法,因为 byte 只有一个字节,用不到这个方法。

java
@IntrinsicCandidate
public static short reverseBytes(short i) {
    return (short) (((i & 0xFF00) >> 8) | (i << 8));
}

看代码可以比较清晰知道其功能为将其前后的 8 个 bit 互换下位置。即,如果参数的二进制为 0000 0000 1111 1111,其结果为 1111 1111 0000 0000

java
System.out.println(Short.reverseBytes((short) 255))); // -256

不太清楚这个方法的使用场景,如果不是看源码都不知道有这个方法。

Short 类型也有对应的内部缓存类 ShortCache,不过由于 short 型有 6 万多个数字,所以不可能将所有的都缓存下来,而是和 ByteCache 一样,只缓存了 -128 到 127 一共 256 个数字。

其它方法和 Byte 区别不大,就直接跳过了。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.