有关“==”和“equals“

有关“==”和“equals"


引入
最近在重写ArrayList时发现一个问题,为什么源码在调用indexOf()时会先判断传入的参数是不是==null,确认不是才可以调用equals()方法
源码如下:

public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

先解释一下为什么要判断传入的参数是不是==null,确认不是才可以调用equals()方法。
我们知道java中对equals的定义: 对于任何非空引用值 x,x.equals(null) 都应返回 false。如果对象为null那系统运行就会报空指针异常。
也就是说null.equals(a);错误的。比较a是否为null应该是a.equals(null);

void compare() {
        String s1=new String("abc");
        String s2=new String("abc");

        String s3="abc";//在常量池中
        String s4="abc";

        boolean falg1=(s1==s2);
        boolean falg2=(s1.equals(s2));
        boolean falg3=(s3==s4);
        boolean falg4=(s3.equals(s4));
        System.out.println("输出:");
        System.out.println("s1与s2 == :" + falg1);
        System.out.println("s1与s2 equals :" + falg2);
        System.out.println("s3与s4 == :" + falg3);
        System.out.println("s3与s4 equals :" + falg4);
    }

在这里插入图片描述

输出:
s1与s2 == :false
s1与s2 equals :true
s3与s4 == :true
s3与s4 equals :true

“==”和“equals"小结

==是一个关系运算符,
如果比较的两端都为基本类型,则判断两者的值是否相等,
如果比较的两端都为包装类(引用类)的话,则比较两者所指向对象的地址是否相同


equals方法
首先,任何对象都可以调用equals ()方法,但是对象在调用方法的时候,如果对象为
null那系统运行就会报空指针异常
如果没有,则比较两者所指向对象的地址是否相同.(就是使用==来比较的)
如果这个对象所在的类重写了equals方法,则按照重写的方法进行比较

衍生问题

Integer为127相等,为128时不相等
测试代码如下:

public class Test {
    public static void main(String[] args) {
        Integer a=127;
        Integer b=127;
        Integer c=128;
        Integer d=128;
        int e=1000;
        int f=1000;
        System.out.println(a==b);
        System.out.println(c==d);
        System.out.println(e==f);
    }
}

输出如图:
在这里插入图片描述
可以看到当Integer为127时还是相等的,但当Integer为128时就不相等了,而int则没有这个问题。

遇事不断看源码:

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

没看懂IntegerCache?那就再看源码

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() {}
    }

这下看懂了吧。没懂也不要紧,诸君,且听 龙吟 我细细道来。
看到这两行代码了没有

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

首先在当jvm启动时静态类和静态块会优先加载(其先后顺序在编译期之前)
执行完后发生了什么?

  1. high = h = 127;
  2. j = low = -128;
  3. cache.length = high - low +1 = 256;
  4. 重点:
    for(int k = 0; k < cache.length; k++)
    cache[k] = new Integer(j++);
    cache[]会实例化将暂存数值在-128到127之间的Integer类型对象。
    并加载到常量池中
    (这就是原因!!!)

cache[]数组只储存了[-128 , 127]的数值,所以对于-128到127之间的int类型,返回的都是同一个Integer类型对象(即地址相同)。

验证地址相同:

public class Test {
    public static void main(String[] args) {
        Integer a=127;
        Integer b=127;
        Integer c=128;
        Integer d=128;
        System.out.println(a==b);
        System.out.print("a = "+System.identityHashCode(a));
        System.out.println("        b = "+System.identityHashCode(b));
        System.out.println(c==d);
        System.out.print("c = "+System.identityHashCode(c));
        System.out.println("        d = "+System.identityHashCode(d));
    }
}

输出如图:
在这里插入图片描述
至于为什么?我觉得这位大佬讲的很有道理:

为什么Java这么设计?我想是出于效率考虑,因为自动装箱经常遇到,尤其是小数值的自动装箱;而如果每次自动装箱都触发new,在堆中分配内存,就显得太慢了;所以不如预先将那些常用的值提前生成好,自动装箱时直接拿出来返回。哪些值是常用的?就是-128到127了。


解决Integer为127相等,为128时不相等
看到这里,大家应该累了,那我也不说废话了。如果要判断Integer是否值相等,直接用equals就好了


public class Test02 {
    public static void main(String[] args) {
        Integer a=-129;
        Integer b=-129;
        Integer c=1000;
        Integer d=1000;
        System.out.println(a.equals(b));
        System.out.println(c.equals(d));
    }
}

输出如图:
在这里插入图片描述


完结撒花~~~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值