您的位置:首页 > 编程语言 > Java开发

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

2016-03-14 10:57 766 查看
              int 为基本类型,Integer是int对应的封装类,或称包装类,是对象。

               int                       Integer

初始值: 0                       null

               基本类型对应的封装类

int(4字节)Integer
byte(1字节)Byte
short(2字节)Short
long(8字节)Long
float(4字节)Float
double(8字节)Double
char(2字节)Character
boolean(未定)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()方法不同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: