首页 > 代码库 > java细节篇(==和equals的区别)

java细节篇(==和equals的区别)

1)当==两边是对象时(String,Integer...),两边比的都是地址
2)当==两边是基本类型时(int,float),两边比的都是值
3)默认equals比的是对象的地址,但是重写的话可以改变成比较值,String和Integer的equals就是重写过的

废话少说,Run!!!

package test;public class Test {    public static void main(String[] args) {                System.out.println("###############对象时比的都是地址################");        TestObj t = new TestObj();        TestObj t2 = new TestObj();        System.out.println(t==t2);//false        System.out.println(t.equals(t2));//false                System.out.println("############基本类型[==]比的是值###########");        int a=1;        float b=1f;        System.out.println(a==b);//true        //  System.out.println(a.equals(b)); 写法错误                System.out.println("##########Integer特殊(equals重写成比较值,但new时==还是比较地址)##########");        Integer i1=0;        Integer i2=0;        System.out.println(i1==i2);//true        System.out.println(i1.equals(i2));//true        Integer i3 = new Integer(0);        Integer i4 = new Integer(0);        System.out.println(i3==i4);//false        System.out.println(i3.equals(i4));//true        System.out.println(i1==i3);//false        System.out.println(i1.equals(i3));//true        System.out.println(i4.equals(i2));//true        int i5 = 0;        System.out.println(i1.equals(i5));//true 和基本int类型比是比值        System.out.println(i1==i5);//true 和基本int类型比也是比值        System.out.println(i3.equals(i5));//true new的和基本int类型比是比值        System.out.println(i3==i5);//true  new的和基本int类型比也是比值        float f6 = 0f;//等同f6=0;        System.out.println(i1.equals(f6));//false 注意结果不同说明equals的重写只是对int类型时是比值        System.out.println(i1==f6);//true        System.out.println(i3.equals(f6));//false 注意结果不同说明equals的重写只是对int类型时是比值        System.out.println(i3==f6);//true                  System.out.println("=======String特殊=======");        String s1="a";        String s2="a";        System.out.println(s1==s2);        System.out.println(s1.equals(s2));        String s3 = new String("a");        String s4 = new String("a");        System.out.println(s3==s4);        System.out.println(s3.equals(s4));        System.out.println(s1==s3);        System.out.println(s1.equals(s3));        System.out.println(s4.equals(s2));                    }}

对于Integer为什么只会对int作值的比较,查看源代码可见:

/**     * 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 =http://www.mamicode.com/= ((Integer)obj).intValue();        }        return false;    }

 

java细节篇(==和equals的区别)