Java基本数据类型包装类(2)

其中"i+5"是数值运算,i首先从对象转换为数值,得到9。而等号左边的i是对象引用,所以还要再将9自动装箱为对象。所以等价于下面的代码:

i = Integer.valueOf(i.intValue()+5);

由此可见,自动装箱、拆箱的特性,极大地增强了可读性。

但自动装箱的过程有一点小细节:当数值在byte范围内(-128-127)时,自动装箱时不会新创建对象。意思是当有一个Integer x对象中的值为3时,它小于127,如果还有一个Integer y,它的值也是3,那么x和y指向同一个对象。

Integer x = new Integer(3); Integer y = new Integer(3); System.out.println(x==y); //false System.out.println(x.equals(y)); //true Integer a = 3; Integer b = 3; System.out.println(a==b); //true System.out.println(a.equals(b)); //true Integer c = 128; Integer d = 128; System.out.println(c==d); //false System.out.println(c.equals(d)); //true

本文永久更新链接地址

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0f7a8a985ddb901b06fdf5f868b88734.html