JAVA中基本数据类型和封装类的区别Integer和Double为例

来源:互联网 发布:淘宝白菜群怎么得佣金 编辑:程序博客网 时间:2024/05/16 04:18

              int 为基本类型,Integer是int对应的封装类,或称包装类,是对象。

               int                       Integer

初始值: 0                       null

               基本类型对应的封装类

int(4字节)Integerbyte(1字节)Byteshort(2字节)Shortlong(8字节)Longfloat(4字节)Floatdouble(8字节)Doublechar(2字节)Characterboolean(未定)Boolean


                那么问题来了   Integer i=1; int ii =1;  i==ii?    true  or flase ?


        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;
         
        System.out.println(i1==i2);//true
        System.out.println(i3==i4);//false

说明i1和i2指向的是同一个对象,而i3和i4指向的是不同的对象


那么问题出现在Integer自动封装时用到的valueOf(int i) 方法

public static Integer valueOf(int i) {        if(i >= -128 && i <= IntegerCache.high)            return IntegerCache.cache[i + 128];        else            return new Integer(i);    }
如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。

因此出现上述结果

Double:

        Double i1 = 100.0;
       Double  i2 = 100.0;
        Double i3 = 200.0;
      Double i4 = 200.0;
         
        System.out.println(i1==i2);//false
        System.out.println(i3==i4);//false

Double与Integer的原理相似,也是要进行自动拆箱和装箱,但是为什么返回的结果不一样?

原因:在某个范围内的整型数值的个数是有限的,而浮点数却不是,两者的valueOf()方法不同。

0 0
原创粉丝点击