一、包装类
JAVA提供了俩种数据类型:基本数据类型和引用数据类型
引用数据类型,其实就是各种JAVA jdk提供的类
包装类只要用在泛型< E >中
-
包装类
很多时候,我们需要创建对象来解决问题,如ArrayList< E >,其中E必须是一个引用数据类型,如果想使用基本数据类型,就必须使用基本数据类型对应的引用数据类型,即包装类。
包装类在将基本数据类型包装为引用数据类型的同时,也定义了对基本数据类型操作的方法 -
基本数据类型对应的包装类
本类型 包装类 byte Byte short Short int Integer long Long float Float doule Double char Character boolean Boolean -
装箱与拆箱
装箱:
(1)使用构造方法包装类名(int value) //构造一个新分配的 Integer 对象,它表示指定的 int 值。 包装类名(String s) //构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。 //这里的字符串中的内容必须和包装类对应的基本数据类型一致 //如Integer("100") 正确,Integer("fg"),Integer("1.5")错误
(2)使用静态方法
static 包装类名 valueOf(int i) //返回一个表示指定的 int 值的 包装类 的 实例。 static 包装类名 valueOf(String s) //返回保存指定的 String 的值的 包装类 的 对象。作用:把字符串转换为对应类型的数据
拆箱:使用成员方法
格式:基本数据类型 基本数据类型value()
如:int intValue() 以 int 类型返回该 Integer 的值。 byte byteValue() 作为一个 byte 返回此 Byte 的值。
-
自动装箱/自动拆箱
在JAVA5版本之后实现的
自动装箱:直接把基本数据类型的值赋值给包装类
自动拆箱:包装类不能进行基本运算,但它会自动转换为基本数据类型 -
示例
package linxu.day15; import java.util.ArrayList; public class demomeian { public static void main(String[] args) { //装箱与拆箱 Integer integer=new Integer(10); Integer integer1=new Integer("100"); Integer integer2=Integer.valueOf(10); Integer integer3 = Integer.valueOf("10"); int i = integer.intValue(); //自动装箱与自动拆箱 Integer integer4=5;//自动装箱不需要new,直接赋值即可 integer4+=5; //相当于:integer4= integer4+5;-->Integer temp=integer4.intValue()+5-->integer4=new Integer(temp) //可以看出自动拆箱的步骤其实很多,只是省略了 ArrayList<Integer> list=new ArrayList<>(); list.add(1);//相当于自动装箱 Integer integer5=list.get(0);//正常情况下Integer接受 int in=list.get(0);//自动拆箱 相当于list.get(0).intValue(); } }
二、String与基本数据类型的转换
-
基本数据类型转换为String
(1)基本数据类型直接和字符串拼接,如:String s=56+"sbs";
(2)使用包装类的toString静态方法String toString(int i); //返回一个 String 对象。 所有包装类都有toString方法
(3)使用String类的静态方法
String valueOf(int i);
-
String转换为基本数据类型
使用parse方法
使用包装类的静态方法static byte parseByte(String s) // 将 string 参数解析为有符号的十进制 byte。 static int parseInt(String s) // 将字符串参数作为有符号的十进制整数进行解析 //除了Character都有parse方法