包装类

107 阅读2分钟
  1. 何为包装类,简单一点来说,就是基本数据类型所对应的引用数据类型
  2. Object类可以统一所有的数据,包装类的默认值为null
  3. 基本数据类型对应的引用数据类型
基本数据类型包装类型
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

类型转换与装箱、拆箱

装箱:基本数据类型转换为引用数据类型

拆箱:引用数据类型转换为基本数据类型

package com.Class.packagingClass;

public class boxAndnobox {

    public static void main(String[] args) {

        //JDK1.5之前

        //类型转换:装箱 --> 基本类型转换为引用类型
        int num1 = 20;
        Integer integer = new Integer(num1);
        Integer integer1 = Integer.valueOf(num1);
        System.out.println("装箱");
        System.out.println(integer);
        System.out.println(integer1);

        //类型转换:拆箱 --> 引用类型转换为基本类型
        Integer a = new Integer(23);
        int result = a.intValue();
        System.out.println("拆箱");
        System.out.println(result);

        //JDK1.5之后:自动装箱和自动拆箱

        //自动装箱
        int aa = 10;
        Integer s = aa;
        System.out.println("自动装箱");
        System.out.println(s);

        //自动拆箱
        int in = s;
        System.out.println("自动拆箱");
        System.out.println(in);

    }
}

输出结果:

整数缓冲区

  • Java预先创建了256个常用的整数包装类型对象
  • 在实际应用中,对已创建的对象进行复用
package com.Class.packagingClass;

public class IntegerTest {
    public static void main(String[] args) {
        Integer in1 = new Integer(100);
        Integer in2 = new Integer(100);
        System.out.print("in1==in2的结果:");
        System.out.println(in1==in2);//比较的是 in1和in2的地址

        System.out.println("======================");
        //自动装箱
        Integer in3 = 100;// --> Integer in3 =Integer.valueOf(100)
        Integer in4 = 100;// --> Integer in4 =Integer.valueOf(100)
        System.out.print("in3==in4的结果:");
        System.out.println(in3==in4);//比较的是值

        System.out.println("======================");
        //自动装箱
        Integer in5 = 200;// --> Integer in5 =new Integer(200)
        Integer in6 = 200;// --> Integer in6 =new Integer(200)
        System.out.print("in5==in6的结果:");
        System.out.println(in5==in6);//比较的是地址

        //----> Integer.valueOf(number)中 number有范围:-127~127 超出范围 就是按照Integer integer =new Integer(number)的形式来创建Integer

    }
}

输出结果: