Java8源码 java.lang 包 08、Short类

本文详细介绍了Java8中Short类的结构和功能,包括静态内部类ShortCache、构造方法、常用方法如toString、parseShort、valueOf等。重点解析了ShortCache的缓存机制,以及各种转换和比较方法的实现,如compareTo和reverseBytes。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

Short 类将基本类型 short 的值包装在一个对象中。一个 Short 类型的对象只包含一个类型为 short 的字段。

此外,该类还为 shortString 的相互转换提供了几种方法,并提供了处理 short 时非常有用的其他一些常量和方法。

Short 类的设计几乎和 Byte类一模一样

类的定义

public final class Short extends Number implements Comparable<Short>

Short 类继承了抽象父类 Number,并实现了 Comparable 接口的 compareTo 方法用于对象之间的比较。

静态内部类 ShortCache

    private static class ShortCache {
        private ShortCache(){}

        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));
        }
    }

私有的静态内部类 ShortCache,只能在本类中使用。内部类 ShortCache 定义了一个由 static final 修饰的 Short 类型数组cache ,并且在静态代码内初始化了 256 个 Short 对象。由于 short 的范围为 32768-32767,全部缓存的话会占用较大的内存空间,所以只缓存了常用的 ~128-127 范围内的数字。这个范围内的 Short 对象直接从缓存中获取,而对于范围外的 Short 对象则需要创建新的对象。

成员变量

    private final short value;

用于保存 Short 对象的值,被 final 修饰表示其初始化完成后就不能再被修改。

类变量

    // byte的边界值
	public static final short   MIN_VALUE = -32768;
    public static final short   MAX_VALUE = 32767;

	//	用于二进制补码形式表示short值的比特数。 
    public static final int SIZE = 16;	
	// 用于二进制补码形式表示short值的字节数。 
    public static final int BYTES = SIZE / Byte.SIZE;

构造方法

    public Short(short value) {
        this.value = value;
    }
    
    public Short(String s) throws NumberFormatException {
        this.value = parseByte(s, 10);
    }

和 Boolean 类似,最终都是将传入的数据赋值给了 value

其他方法

静态toString(short)方法

    public static String toString(short b) {
        return Integer.toString((int)b, 10);
    }

注意,这不是对 Object 类中的 toString 方法进行的重写。Object 的 toString 方法没有参数。这是 Short 类自定义的 toString 方法,它调用了 Integer 的 toString 方法将 short 数据转换为对应的字符串形式。

parseByte(String s) 与 parseByte(String, int)

	public static byte parseByte(String s) throws NumberFormatException {
        return parseByte(s, 10);
    }

	public static byte parseByte(String s, int radix) throws NumberFormatException {
        int i = Integer.parseInt(s, radix);
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                "Value out of range. Value:\"" + s + "\" Radix:" + radix);
        return (short)i;
    }

调用 Integer.parseInt(s, radix) 将合法的字符串转换为指定进制的 short 值(默认十进制)。

上面的合法字符串要求是以十进制表示的、范围在 -32768~32767 的数字。即十进制的 byte 值。
下面的合法字符串要求是指定基数的、范围在 -32768~32767 的数字。
不合法的参数会抛出 NumberFormatException 异常:

        System.out.println(Short.parseShort("7FFF", 16));
        System.out.println(Short.parseShort("32767", 10));

        //java.lang.NumberFormatException: Value out of range
        System.out.println(Short.parseShort("8000", 16));
        System.out.println(Short.parseShort("32768"));

valueOf(short)

    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

同 Boolean 类,创建 Short 实例时应优先使用该方法而非构造方法 Short(short value),因为它在取值为 -128~127 时必走缓存,性能好。

valueOf(String) 与 valueOf(String, int)

	public static Short valueOf(String s) throws NumberFormatException {
        return valueOf(s, 10);	
    }

	public static Short valueOf(String s, int radix) throws NumberFormatException {
        return valueOf(parseShort(s, radix));
    }

底层调用的还是 parseByte 方法。

重写父类的xxxValue()

	// 由于short长度大于byte所以这里可以会出现溢出的情况
    public byte byteValue() {
        return (byte)value;
    }
    public short shortValue() {
        return value;
    }
    public int intValue() {
        return (int)value;
    }
    public long longValue() {
        return (long)value;
    }
    public float floatValue() {
        return (float)value;
    }
    public double doubleValue() {
        return (double)value;
    }

除 shortValue() 方法外,其他都通过强制类型转换转换成了对应的基本类型。

toString()

    public String toString() {
        return Integer.toString((int)value);
    }

hashCode()

    @Override
    public int hashCode() {
        return Short.hashCode(value);
    }

	public static int hashCode(Short value) {
        return (int)value;
    }

相当于调用了 intValue() 方法,返回的就是 Short 对象表示的数值。

equals()

    public boolean equals(Object obj) {
        if (obj instanceof Short) {
            return value == ((Short)obj).shortValue();
        }
        return false;
    }

都是 Short 类型,且对应的 value 值都相等,则两者是同一个对象。

compareTo() 与 compare(short, short)

    public int compareTo(Short anotherShort) {
        return compare(this.value, anotherShort.value);
    }
	
	public static int compare(short x, short y) {
        return x - y;
    }

比较此 Short 对象和入参 Short 对象的数值大小。相等返回0,前者大则返回正数,后者大则返回负数。

reverseBytes(short)

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

将short类型的低8位与高8位互换

  • (i & 0xFF00) >>8 低 8 位位置 0,高 8 位为不变;然后右移 8 位,得到高 8 位的数据
  • i << 8 左移 8 位,低位补 0
  • 最后两者做或运算,结果截断取低 8 位,即得到了原 short 值的高 8 位。

转换成无符号整数

    public static int toUnsignedInt(short x) {
        return ((int) x) & 0xffff;
    }
    
    public static long toUnsignedLong(short x) {
        return ((long) x) & 0xffffL;
    }

见名知意,在 IO 操作时用到的情况较多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值