Integer执行++操作解析

来源:互联网 发布:篮球比赛赛程软件 编辑:程序博客网 时间:2024/06/05 17:40

当我们对基本类型int的包装类进行自增操作,返回的值不是原来的对象:

package com.qianqiang;public class Demo {    public static void main(String[] args) {    Integer inttest=new Integer(15);    Integer inttest2=inttest++;    System.out.println(inttest==inttest2);}}

答案输出的是false,这是因为Integer执行自加操作的时候,是要进行拆箱操作即调用Integer的intValue返回基本类型数据,执行完自增以后,再调用Integer的装箱操作即调用valueOf重新创建对象。当然如果值的范围是在(-128-127)之间调用Integer已经缓存的对象,上面的代码中返回inttest2返回15的Integer缓存的对象。而此时的inttest因为值自增了1,变为16,所以要调用装箱操作,返回Integer中的已经缓存的16对应的Integer对象。





0 0