java 中基本数据类型与包装类的对应关系是固定的,每种基本类型都有唯一的包装类。具体做法是直接引用对应的类名,例如 int 对应 integer,double 对应 double。这种映射在编译期自动处理,通过自动装箱(auto-boxing)和拆箱(auto-unboxing)机制实现无缝转换。开发者只需记住这八组对应关系即可,无需手动实例化或调用转换方法,除非需要显式控制对象创建或使用特定 api。

byte 和 short 的包装类分别是什么
byte 的包装类是 Byte,short 的包装类是 Short。这两个类型属于较小的整数范围,它们的包装类同样支持自动装箱和拆箱。在实际编码中,如果你需要将 byte 值存入集合,编译器会自动将其转换为 Byte 对象。反之,从集合取出时也会自动转回 byte。这种对应关系确保了类型安全,同时保持了代码的简洁性。

public class WrapperExample { public static void main(String[] args) { byte b = 10; short s = 20; // 自动装箱 Byte boxedByte = b; Short boxedShort = s; // 自动拆箱 byte unboxedByte = boxedByte; short unboxedShort = boxedShort; System.out.println("Byte: " + unboxedByte); System.out.println("Short: " + unboxedShort); } }
char 和 boolean 的包装类分别是什么
char 的包装类是 Character,boolean 的包装类是 Boolean。char 用于表示单个 Unicode 字符,其包装类 Character 提供了如 isDigit、isLetter 等实用方法。boolean 表示逻辑值 true 或 false,其包装类 Boolean 允许将布尔值作为对象处理。这两者与其他数值类型不同,Character 没有算术运算,Boolean 也没有数学意义,但它们都遵循相同的自动转换规则。

public class CharBoolExample { public static void main(String[] args) { char c = 'A'; boolean flag = true; // 自动装箱 Character boxedChar = c; Boolean boxedFlag = flag; // 自动拆箱 char unboxedChar = boxedChar; boolean unboxedFlag = boxedFlag; System.out.println("Char: " + unboxedChar); System.out.println("Boolean: " + unboxedFlag); } }
Integer 缓存对 equals 比较有什么影响
Integer 缓存会影响使用 == 运算符时的比较结果,但不会影响 equals 方法的正确性。当整数值在 -128 到 127 之间时,JVM 会复用缓存中的 Integer 对象,导致 == 比较返回 true。超出此范围的数值则会创建新对象,== 比较返回 false。因此,在比较 Integer 对象时,应始终使用 equals 方法以避免潜在 bug。这一行为源于 IntegerCache 的实现,旨在优化常见小整数的内存使用。
public class IntegerCacheTest { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 200; Integer i4 = 200; System.out.println(i1 == i2); // true, cached System.out.println(i3 == i4); // false, new objects System.out.println(i1.equals(i2)); // true System.out.println(i3.equals(i4)); // true } }
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











