面试官:条件 a == (Integer) 1 && a == (Integer) 2有可能为true吗?

最近无意间看到一个有趣的帖子:

有这么个条件:条件 a == (Integer) 1 && a == (Integer) 2有可能为true吗?

int a = 1;
        if (a == 1 && a ==  2) {
            System.out.println("true");
        }

这是一个 JS 社区抛出来的问题。这里我改成 java 的方式,我的第一感觉确实为false啊,怎么可能 a 的值即为 1,又为2?似乎是一个无稽之谈

不过后来深入思考一下,发现这类问题有点意思…

如果这里将基本数据类型转为包装类,转化后的值可不可能是一个值呢?

发话不多说,先上代码:

public static void main(String[] args) throws InterruptedException {
		Class cache = Integer.class.getDeclaredClasses()[0];// 1
        Field c;
        try {
            c = cache.getDeclaredField("cache"); // 2
            c.setAccessible(true);// 2
            Integer[] array = (Integer[]) c.get(cache);// 2
            array[130] = array[129];
            int a = 1;
            if (a == (Integer) 1 && a == (Integer) 2) {
                System.out.println("true");
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

	}

输出这段代码发现真的好神奇,真的输出为 true,那么到底是怎么实现的呢?

首先调用 1 处代码拿到 Integer 类中某个内部类,看了 Integer 类,这个类中只有一个静态内部类,那就是IntegerCache 类。

接着调用 2 处拿到 IntegerCache 中的 cache 变量,并强制转化为 Integer 数组。

最重要的一步来了。

array[130] = array[129];

这一步为什么说这么重要呢,别急,我们看一下JDK 中 Integer 类的源码:

public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }
 
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);

在解析时调用了 IntegerCache 这个类,这个类时 Integer 的一个内部静态类,用来缓存 [-128-127] 这些数字

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */
 
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
 
        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;
        }
 
        private IntegerCache() {}
    }

从这里我们可以知道,这个内部类中的 cache 数组,cache[129]=1,cache[130]=2。

这个内部类到底干什么的呢?

比如我们上面代码中 (Integer) 1 ,将会执行自动装箱操作,相当于调用了我们上面贴出的 Integer.valueOf 方法的代码。

简单点说,若是整型字面量的值在 [-128,127] 之间,那么不会 new 新的 Integer 对象,而是直接引用常量池中的Integer 对象,如果 i 属于 [-128,127] 区间时,将会返回 cache 数组中对应的值,例如 i=0 时,返回cache[128],这个值等于0,否则的话,重新创建一个 Integer 实例。将 [-128,127] 缓存在 Integer 内部类 IntegerCache 里的数组中,有需要直接取。

所以,现在 a 等于 1,(Integer)1 等于 cache[129],也就是等于 new Integer(1) ,拆箱后等于 1

(Integer)2 等于 cache[130] ,在我们利用反射修改数组的值后,此时 cache[130] 也等于 new Integer(1),拆箱后还是等于 1

因此,上例中确实可以返回true

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值