Integer实现

今天抽时间对Integer的源码实现进行研究下

从一道经典的题目开始讲起:我们如何进行两个Integer类型的交换?

首先我来演示一种错误的做法

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a =1, b =2;
        System.out.println("before a = " + a +", b = " + b);
        swap1(a,b);
        System.out.println("After a = " + a +", b = " + b);
    }

    private static void swap1(Integer i1, Integer i2) throws NoSuchFieldException, IllegalAccessException {
        Integer temp = i1;
        i1 = i2;
        i2 = temp;
    }
执行结果
before a = 1, b = 2
After a = 1, b = 2

这段代码错误的原因在哪呢?

i1和i2是引用类型,i1和i2两个变量存在栈中,a和b两个变量也存在栈中,其中i1和a指向同一个空间,i2和b之前同一个空间,

在swap1中只是进行了i1和i2指向发生了交换,地址空间并没有发生任何改变,,实际Integer类型的value值是final类型,也无法进行改变,i1和i2指向发生了交换并不会影响到a和b的指向。

第二种方式:我们想到了既然Integer类型的value是final类型,我们可以通过反射了实现交换地址空间中的内容来实现

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a =1, b =2;
        System.out.println("before a = " + a +", b = " + b);
        swap2(a,b);
        System.out.println("After a = " + a +", b = " + b);
    }

    private static void swap2(Integer i1, Integer i2) throws NoSuchFieldException, IllegalAccessException {
        Field field = Integer.class.getDeclaredField("value");
        field.setAccessible(true); //绕过安全检查
        int temp = i1.intValue();
        field.set(i1,i2.intValue());
        field.set(i2,temp);
    }
执行结果:
before a = 1, b = 2
After a = 2, b = 2

执行出来的结果和我们想想的完全不一样,交换后a=2可以理解,但是为什么b=2哪?

首先我们看到set方法的定义:public void set(Object obj, Object value)

可以看出set设置的第二个参数是Object类型,而代码中传第二个参数为int基本类型,因此需要调用Integer.valueOf()转化为包装类型

static final int low = -128;
static final int high;
int h = 127;
high = h;    

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

从源码中可以清晰的看到当数据位于-127和128中间时,从缓存中读取数据,在看缓存数据从何而来

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

 从这段代码中已经可以看出是Integer静态代码块,在启动的时候进行加载

因此也就出现上述的问题,在执行完field.set(i1,i2.intValue());之前,cache[128]=1,cache[129]=2,而执行完field.set(i1,i2.intValue());之后,此时cache[128]=2,cache[129]=1;此时temp=1,对1再进行包装是执行Integer.valueOf(),返回的对应数组位置为cache[128],经过包装后的置为2,因此i2=2;所以得出如上的打印结果a=2,b=2

从这段代码可以分析如果不在-127和128中间时,理论上应该不会出现这个问题。来让我们验证下

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a =200, b =201;
        System.out.println("before a = " + a +", b = " + b);
        swap2(a,b);
        System.out.println("After a = " + a +", b = " + b);
    }

    private static void swap2(Integer i1, Integer i2) throws NoSuchFieldException, IllegalAccessException {
        Field field = Integer.class.getDeclaredField("value");
        field.setAccessible(true); //绕过安全检查
        int temp = i1.intValue();
        field.set(i1,i2.intValue());
        field.set(i2,temp);
    }
执行结果:
before a = 200, b = 201
After a = 201, b = 200

从结果来看我们的猜想是正确的。

从上面我们可以进行进行第三种和第四种方法

第三种方法:如果我们使用的中间变量是Integer类型且是新创建变量,不通过基本类型隐式转化为包装类型,应该可以实现

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a =1, b =2;
        System.out.println("before a = " + a +", b = " + b);
        swap3(a,b);
        System.out.println("After a = " + a +", b = " + b);
    }
    private static void swap3(Integer i1, Integer i2) throws NoSuchFieldException, IllegalAccessException {
        Field field = Integer.class.getDeclaredField("value");
        field.setAccessible(true); //绕过安全检查
        Integer temp = new Integer(i1.intValue());
        field.set(i1,i2);
        field.set(i2,temp);
    }
执行结果
before a = 1, b = 2
After a = 2, b = 1

第四种方法:Integer中提供了setInt方法,可以直接对属性进行赋值,不进行转换为包装类型

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a =1, b =2;
        System.out.println("before a = " + a +", b = " + b);
        swap4(a,b);
        System.out.println("After a = " + a +", b = " + b);
    }
    private static void swap4(Integer i1, Integer i2) throws NoSuchFieldException, IllegalAccessException {
        Field field = Integer.class.getDeclaredField("value");
        field.setAccessible(true); //绕过安全检查
        int temp = i1.intValue();
        field.setInt(i1,i2.intValue());
        field.setInt(i2,temp);
    }
执行结果:
before a = 1, b = 2
After a = 2, b = 1

总结

通过这个题目我们可以得出如下结论:

(1)-127到128中的数据是存储在缓存数组中的,不会进行重新创建,而不在范围内的数据是重新new新的对象

(2)Integer中的value是final类型,要想修改堆地址中的内容,需要通过反射且设置访问权限才可进行操作

(3)-127到128中的数据通过调用valueOf和new出来的原理是不一样的,而不在范围内的数据原理是一样的

(4)可以通过setInt方法进行修改Integer对象的属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值