面试常问 equals和==区别

    技术2022-07-10  131

    equals和==区别

    == 理解

    对于基本类型和引用类型 == 的作用效果是不同的,如下所示: 基本类型:比较的是值是否相同; (基本类型: byte int float char short boolean double long) 引用类型:比较的是引用是否相同; (引用类型:类 接口 数组 枚举 注解 感觉简单点平时用到的除了基本类型都是引用)

    equals理解

    equals 本质上就是 ==,只不过 String 和 Integer 等重写了 equals 方法,把它变成了值比较

    事例
    String a = "abc"; String b = "abc"; String c = new String("abc"); System.out.println(a==b); // true System.out.println(a==c); // false System.out.println(a.equals(b)); // true System.out.println(a.equals(c)); // true

    因为a和b指向同一个地址,所以== 结果为true;c是新new的对象,所以地址不同 ,结果才不一样。而equals重写了== 比较的是两个String的值。

    equals源码
    public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
    Processed: 0.010, SQL: 9