包装类
- 包装类(Wrapper Classes)是Java中用于将基本数据类型(如 int、char、boolean 等)封装为对象的类
- 将基本数据类型转换为对象,以便在需要对象的场景中使用(例如集合类)
- 提供了一些实用的方法(如类型转换、字符串解析等)
主要功能
-
包装类可以将基本数据类型封装为对象,以便在需要对象的场景中使用(例如集合类)
Integer num = new Integer(10); // 将 int 封装为 Integer 对象
自动拆箱和装箱
-
从Java 5开始,引入了自动装箱(Autoboxing)和自动拆箱(Unboxing)机制,使得基本数据类型和包装类之间的转换更加方便
-
自动装箱
自动装箱实际上是调用了包装类的 valueOf() 方法
Integer num = 10; // 等价于 Integer num = Integer.valueOf(10);
//valueOf方法的实现 new了一个Integer对象 public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i); }
-
自动拆箱
自动拆箱实际上是调用了包装类的 xxxValue() 方法(如 intValue())
Integer num = new Integer(10); int value = num; // 等价于 int value = num.intValue();
包装类的常用方法
-
构造方法
Integer num1 = new Integer(10); // 通过 int 值创建 Integer num2 = new Integer("20"); // 通过字符串创建
-
静态方法
int value = Integer.parseInt("123"); // 字符串 -> int Integer num = Integer.valueOf(10); // int -> Integer Integer num2 = Integer.valueOf("20");// 字符串 -> Integer
-
实例方法
Integer num = new Integer(10); int value = num.intValue(); // Integer -> int String str = num.toString(); // Integer -> String
包装类应用场景
- 集合类:集合类(如 ArrayList、HashMap)只能存储对象,不能存储基本数据类型,因此需要使用包装类
- 泛型:泛型只能使用对象类型,不能使用基本数据类型,因此需要使用包装类
- 方法参数:如果方法参数需要接受 null 值,可以使用包装类
Object obj=true? new Integer(1):new Double(2.0) //三元运算符为一个整体
System.out,println(obj) //1.0
包装类和String的类型转换
-
包装类转换为 String
-
使用对象的
toString()
方法。Integer num = 123; String str = num.toString(); // 将 Integer 转换为 String System.out.println(str); // 输出: 123
-
使用
String.valueOf()
方法。Integer num = 123; String str = String.valueOf(num); // 将 Integer 转换为 String System.out.println(str); // 输出: 123
-
使用字符串拼接
Integer num = 123; String str = "" + num; // 将 Integer 转换为 String System.out.println(str); // 输出: 123
-
-
String 转换为包装类
-
使用包装类的
valueOf()
方法。String str = "123"; Integer num = Integer.valueOf(str); // 将 String 转换为 Integer System.out.println(num); // 输出: 123
-
使用包装类的
parseXxx()
方法。String str = "123"; int value = Integer.parseInt(str); // 将 String 转换为 int Integer num = value; // 自动装箱:int -> Integer System.out.println(num); // 输出: 123
-
使用包装类的构造函数(已过时)
-
使用构造函数创建包装类对象会每次都创建一个新的对象,而包装类的 valueOf() 方法通常会利用缓存机制,避免重复创建对象,从而提高性能
String str = "123"; Integer num = new Integer(str); // 将 String 转换为 Integer System.out.println(num); // 输出: 123
-
包装类之间的等值对比
-
== 运算符:比较的是对象的引用(内存地址),而不是对象的值
-
equals() 方法:比较的是对象的值-128
到
127//重写的equals方法 public boolean equals(Object obj) {if (obj instanceof Integer) {return value == ((Integer)obj).intValue();}return false; }
-
包装类与基本数据类型的对比
- 当包装类和基本数据类型进行等值对比时,Java会自动拆箱(Unboxing),将包装类对象转换为基本数据类型,然后进行比较
- == 运算符会将包装类对象自动拆箱为基本数据类型,然后比较它们的值
- a.equals(b) 会将 b 自动装箱为 Integer 对象,然后比较它们的值。
包装类的一些知识点 |
---|
包装类对象中有一些常用常量和方法,比如Integer中的MAX_VALUE |
Character包装类中有一系列判断字符是否为大小写或者为是否为数字、字母或者空格的方法 |
除了Float 和 Double其他包装类都进行了缓存 其中Boolean:true 和 false Character:0 到 127 其他包装类都是-128 到 127 |