ZetCode

Java Short 类

最后修改时间:2025 年 4 月 13 日

java.lang.Short 类是 Java 中基本数据类型 short 的包装类。 它提供了在 short 值和 String 表示之间进行转换的方法,以及各种实用方法。

Short 对象包含一个 short 类型的字段。 当您需要将 short 视为对象时,例如在集合中或使用反射时,此类非常有用。 它还为 short 可以容纳的最小值和最大值提供了常量。

Short 类方法

Short 类提供了多个静态和实例方法来处理 short 值。 关键方法包括 parseShortvalueOftoStringcompare 以及各种转换方法。

public final class Short extends Number implements Comparable<Short> {
    public static final short MIN_VALUE = -32768;
    public static final short MAX_VALUE = 32767;
    
    public static short parseShort(String s) {...}
    public static Short valueOf(short s) {...}
    public static Short valueOf(String s) {...}
    public static String toString(short s) {...}
    public static int compare(short x, short y) {...}
    public static short reverseBytes(short i) {...}
    public byte byteValue() {...}
    public short shortValue() {...}
    public int intValue() {...}
    public long longValue() {...}
    public float floatValue() {...}
    public double doubleValue() {...}
    public int compareTo(Short anotherShort) {...}
    public boolean equals(Object obj) {...}
    public int hashCode() {...}
    public String toString() {...}
}

上面的代码显示了 Short 类提供的主要方法和常量。 这些方法允许以各种方式解析、比较、转换和操作 short 值。

创建 Short 对象

在 Java 中有几种创建 Short 对象的方法。 您可以使用构造函数、valueOf 方法或自动装箱。 valueOf 方法通常是首选,因为它们可能会缓存经常使用的值。

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Using constructor (deprecated in Java 9)
        Short s1 = new Short((short) 100);
        
        // Using valueOf method
        Short s2 = Short.valueOf((short) 200);
        Short s3 = Short.valueOf("300");
        
        // Using autoboxing
        Short s4 = 400;
        
        System.out.println("s1: " + s1);
        System.out.println("s2: " + s2);
        System.out.println("s3: " + s3);
        System.out.println("s4: " + s4);
        
        // Accessing constants
        System.out.println("Min value: " + Short.MIN_VALUE);
        System.out.println("Max value: " + Short.MAX_VALUE);
    }
}

此示例演示了创建 Short 对象的不同方法。 请注意,自 Java 9 以来,构造函数方法已被弃用。 valueOf 方法和自动装箱是首选方法。 我们还展示了 MIN_VALUE 和 MAX_VALUE 常量。

解析 Short 值

Short 类提供了用于解析 short 值的 String 表示形式的方法。 parseShort 方法将 String 转换为基本 short 类型,而 valueOf 返回一个 Short 对象。 两者都可以处理不同的基数(数字基数)。

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Parsing decimal strings
        short s1 = Short.parseShort("123");
        Short s2 = Short.valueOf("456");
        
        // Parsing hexadecimal strings
        short s3 = Short.parseShort("1A", 16);
        Short s4 = Short.valueOf("FF", 16);
        
        System.out.println("s1: " + s1);
        System.out.println("s2: " + s2);
        System.out.println("s3: " + s3);
        System.out.println("s4: " + s4);
        
        try {
            // This will throw NumberFormatException
            Short.parseShort("32768"); // Exceeds MAX_VALUE
        } catch (NumberFormatException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

此示例显示了如何将 String 值解析为 short 值。 我们演示了十进制和十六进制解析。 该示例还包括对超出 short 的有效范围(-32768 到 32767)的值的错误处理。

比较 Short 值

可以使用 comparecompareTo 方法比较 Short 值。 静态 compare 方法适用于基本 short 类型,而 compareTo 是 Short 对象的实例方法。

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        short a = 100;
        short b = 200;
        Short s1 = Short.valueOf(a);
        Short s2 = Short.valueOf(b);
        
        // Comparing primitive shorts
        int result1 = Short.compare(a, b);
        System.out.println("compare(100, 200): " + result1);
        
        // Comparing Short objects
        int result2 = s1.compareTo(s2);
        System.out.println("100.compareTo(200): " + result2);
        
        // Equality comparison
        Short s3 = Short.valueOf((short) 100);
        System.out.println("s1.equals(s3): " + s1.equals(s3));
        System.out.println("s1 == s3: " + (s1 == s3)); // May be true due to caching
    }
}

此示例演示了比较 short 值的不同方法。 compare 方法返回负值、零或正值,具体取决于第一个参数是小于、等于还是大于第二个参数。 请注意,== 比较的是对象引用,而不是值。

转换 Short 值

Short 类提供了将 short 值转换为其他基本类型的方法。 这些方法继承自 Number 类,包括 byteValueintValuelongValue 等。

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        Short s = Short.valueOf((short) 12345);
        
        // Converting to other primitive types
        byte b = s.byteValue(); // May lose information
        int i = s.intValue();
        long l = s.longValue();
        float f = s.floatValue();
        double d = s.doubleValue();
        
        System.out.println("byteValue: " + b);
        System.out.println("intValue: " + i);
        System.out.println("longValue: " + l);
        System.out.println("floatValue: " + f);
        System.out.println("doubleValue: " + d);
        
        // Converting to String
        String str1 = s.toString();
        String str2 = Short.toString((short) 54321);
        
        System.out.println("toString: " + str1);
        System.out.println("Short.toString: " + str2);
    }
}

此示例显示了如何将 Short 值转换为其他基本类型和 String。 请注意,转换为 byte 可能会丢失信息,因为 byte 的范围(-128 到 127)比 short 小。 toString 方法提供了值的 String 表示形式。

字节操作

Short 类提供了 reverseBytes 方法来反转 short 值中的字节顺序。 这对于处理不同的字节顺序表示(字节序)很有用。

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        short original = (short) 0x1234;
        short reversed = Short.reverseBytes(original);
        
        System.out.printf("Original: 0x%04x\n", original);
        System.out.printf("Reversed: 0x%04x\n", reversed);
        
        // Practical example: reading little-endian data
        byte[] data = {0x34, 0x12}; // Little-endian representation of 0x1234
        short value = (short) ((data[1] & 0xFF) << 8 | (data[0] & 0xFF));
        
        System.out.printf("Constructed value: 0x%04x\n", value);
    }
}

此示例演示了对 short 值进行的字节操作。 reverseBytes 方法交换 short 值的两个字节。 我们还展示了如何从小端字节顺序构造一个 short 值,这在从文件或网络流读取二进制数据时很常见。

哈希码和相等性

Short 类重写了 hashCodeequals 以提供正确的基于值的比较和哈希。 如果两个 Short 对象表示相同的 short 值,则它们相等,无论它们是否是同一个对象。

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        Short s1 = Short.valueOf((short) 100);
        Short s2 = Short.valueOf((short) 100);
        Short s3 = Short.valueOf((short) 200);
        
        // Equality tests
        System.out.println("s1.equals(s2): " + s1.equals(s2));
        System.out.println("s1.equals(s3): " + s1.equals(s3));
        
        // Hash codes
        System.out.println("s1.hashCode(): " + s1.hashCode());
        System.out.println("s2.hashCode(): " + s2.hashCode());
        System.out.println("s3.hashCode(): " + s3.hashCode());
        
        // Identity vs equality
        System.out.println("s1 == s2: " + (s1 == s2)); // May be true due to caching
    }
}

此示例演示了 Short 对象的相等性和哈希行为。 equals 方法比较包装的 short 值,而 hashCode 返回 short 值本身作为哈希码。 请注意,由于缓存经常使用的 Short 对象,== 可能会为相等的值返回 true。

来源

Java Short 类文档

在本文中,我们通过实际示例介绍了 Java Short 类。 在使用集合、泛型或需要 short 值的对象表示形式时,Short 类至关重要。 了解其方法对于正确的 Java 开发非常重要。

作者

我叫 Jan Bodnar,是一位拥有多年领域经验的敬业程序员。 我于 2007 年开始撰写编程文章,此后撰写了超过 1,400 篇文章和八本电子书。 凭借超过八年的教学经验,我致力于分享我的知识并帮助他人掌握编程概念。

列出所有Java教程