java自动装箱和拆箱

基本数据类型,如int,float,double,boolean,char,byte,不具备对象的特征,不能调用方法。
装箱:将基本类型转换成包装类对象
int i=10;
Integer x=new Integer(i);手动装箱
Integer y=10;自动装箱
 
拆箱:将包装类对象转换成基本类型的值
Integer j=new Integer(8);
int m=j.intValue();//手动拆箱
int n=j;//自动拆箱
 
 
java为什么要引入自动装箱和拆箱的功能?又是怎么实现的呢?
主要是用于java集合中,List<Inteter> list=new ArrayList<Integer>();
list集合如果要放整数的话,只能放对象,不能放基本类型,因此需要将整数自动装箱成对象。
实现原理:javac编译器的语法糖
 
public class Main {
    public static void main(String[] args) {
         
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}
//结果为:true false
 
在通过Integer.valueOf()方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用(位于堆对象池中);否则创建一个新的Integer对象(创建在java堆中)。上面的代码中i1和i2的数值为100,因此会直接从cache中取已经存在的对象,所以i1和i2指向的是同一个对象,而i3和i4则是分别指向不同的对象。
 
public class Main {
    public static void main(String[] args) {
         
        Double i1 = 100.0;
        Double i2 = 100.0;
        Double i3 = 200.0;
        Double i4 = 200.0;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}
//结果为:false false
为什么Double类的valueOf方法会采用与Integer类的valueOf方法不同的实现呢?很简单:在某个范围内的整型数值的个数是有限的,而浮点数却不是。
 
public class Main {
    public static void main(String[] args) {
         
        Boolean i1 = false;
        Boolean i2 = false;
        Boolean i3 = true;
        Boolean i4 = true;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}
//结果为:true true
至于为什么是这个结果,同样地,看了Boolean类的源码也会一目了然。下面是Boolean的valueOf方法的具体实现:
 
 
public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }
 
 
 
public class H {
 
public static void main(String[] args) {
 
 
        Integer m=10;
        int n=10;
        System.out.println(m==n);
}
}
//结果为:true
原文地址:https://www.cnblogs.com/james111/p/6607400.html