拆箱与装箱

    技术2023-12-14  79

    概念:

    装箱:基本数据类型转换为包装类 拆箱:包装类类型转换为基本数据类型

    public class Test { public static void main(String[] args) { // 装箱:基本数据类型转换为包装类 Integer s = 1; // 拆箱:包装类类型转换为基本数据类型 int ss = s; } }

    特点:

    一:缓存

    Java中只是对部分基本数据类型对应包装类的部分数据进行了缓存: 1、byte、short、int和long所对应包装类的数据缓存范围为 -128~127( 2、float和double所对应的包装类没有数据缓存范围; 3、char所对应包装类的数据缓存范围为 0~127; 4、boolean所对应包装类的数据缓存为true和false;

    public class Test { public static void main(String[] args) { // 缓存: // 1、Byte Short Integer Long -128~127 Integer a = 127; Integer b = 127; System.out.println(a == b); a = new Integer(127); b = new Integer(127); System.out.println(a == b); // 2、Float Double 不缓存 // 3、Character 0~127 // 4、Boolean缓存 Boolean m = true; Boolean n = true; System.out.println(m == n); } } //输出结果: //true //false //true

    二:自动拆箱

    public class Test { public static void main(String[] args) { // 自动拆箱:和基本数据类型比较时自动变成基本数据类型 int c = 128; Integer cc = 128; Integer ccc = new Integer(128); System.out.println(c == cc); System.out.println(c == ccc); System.out.println(cc == ccc); } } //输出结果: //true //true //false
    Processed: 0.012, SQL: 9