Integer你需要知道的(== equals hashCode)

Interger

String你需要知道的看这个

猜猜结果是什么?

public interface A {
    public static void main(String[] args) {
        Integer a=127;
        Integer b=127;
        Integer c=221;
        Integer d=221;
        System.out.println(a==b);
        System.out.println(a.equals(b));
        System.out.println(c==d);
        System.out.println(c.equals(d));
    }
}
true
true
false
true

知道为什么吗?

  /**
     * 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.
     */
注释的翻译是(有道):
*缓存支持对象标识语义的自动装箱之间的值
*根据JLS要求-128127()
缓存在第一次使用时被初始化。缓存的大小
*可能由{@code -XX:AutoBoxCacheMax=}选项控制。
*在虚拟机初始化时,java.lang.Integer.IntegerCache.high属性
*可以设置和保存在私有系统属性在
* sun.misc.VM类。


    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() {}
    }
  • 我的理解是在-128到127时候只会有一个地址,这些在缓冲区中存有,不是这个范围的,每次都会去重新创建一个空间,那么这范围外的值比较的时候他们的地址是不一样的.

但是为什么两个221的equal方法比较的时候是true?

  • 因为Integer和String一样重写了equals方法
   /**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is an {@code Integer} object that
     * contains the same {@code int} value as this object.
     *
     * @param   obj   the object to compare with.
     * @return  {@code true} if the objects are the same;
     *          {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

那么hashCode是不是也要变?

  • 那必然,重写equals必须重写hashCode
public class A {
    public static void main(String[] args) {
        Integer c=221;
        Integer d=221;
        System.out.println(c.hashCode()==d.hashCode());
        System.out.println(d.hashCode());
    }
}

  • 运行结果
true
221
  • 看重写的源码你就明白了,返回的hashCode就是他的值
    /**
     * Returns a hash code for this {@code Integer}.
     *
     * @return  a hash code value for this object, equal to the
     *          primitive {@code int} value represented by this
     *          {@code Integer} object.
     */
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    /**
     * Returns a hash code for a {@code int} value; compatible with
     * {@code Integer.hashCode()}.
     *
     * @param value the value to hash
     * @since 1.8
     *
     * @return a hash code value for a {@code int} value.
     */
    public static int hashCode(int value) {
        return value;
    }

那么new的时候== equals又有啥区别

public class A {
    public static void main(String[] args) {
        Integer a=new Integer(5);
        Integer b=new Integer(5);
        Integer c=new Integer(128);
        Integer d=new Integer(128);
        System.out.println(a==b);
        System.out.println(c==d);
        System.out.println(a.equals(b));
        System.out.println(c.equals(d));
    }
}
false
false
true
true
  • new的时候每次都会创建一个地址,两次new的在堆中地址肯定不同,这个和String有点类似.

下面这个结果你应该直接就能秒出来了吧

public class A {
    public static void main(String[] args) {
        Integer a=new Integer(5);
        Integer b=new Integer(5);
        Integer c=new Integer(128);
        Integer d=new Integer(128);
        System.out.println(a.hashCode());
        System.out.println(a.hashCode()==b.hashCode());
        System.out.println(c.hashCode());
        System.out.println(c.hashCode()==d.hashCode());

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值