优秀的编程知识分享平台

网站首页 > 技术文章 正文

转行程序员|面试官:Long类型是比较值用 == 还是 equals有什么区别

nanyue 2024-08-01 22:54:47 技术文章 5 ℃

面试官:Long类型是比较值用 == 还是 equals, 有什么区别?

答:对于对象比较,要看equals重写的方法

    public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }


对于Long的重写方法来说,equals比较的先比较类型,然后把被比较的对象转换成long基本类型,然后用==比较值大小,所以,Long 用equals比较值。long 用 == 比较值。

其他对象类型同理,对于该类型对象的比较,默认情况下,也就是没有复写 Object 类的 equals 方法,使用 == 和 equals 比较是一样效果的,都是比较的是它们在内存中的存放地址

这里要注意:Java 中 integer 范围取值要在-128到+127 ,而我们赋的值是 128 ,此时变量并不在常量区定义。所以两个变量的内存地址不同,== 返回 false。这是因为Inetger有cache。

    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() {}
    }
最近发表
标签列表