JAVA面试题:equals()方法和== 区别

http://bbs.csdn.net/topics/390000725

总结:

equals在没重写之前和==一样,重写之后,equals只要内容一样即为true

equals跟==一般情况下是等价的,但是对于String类型,它重写了equals方法,比较的是内容。默认情况下两个都是比较的引用地址,除非你重写equals方法。

equals源码:

 public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
            return false;
        }
        return true;
        }
    }
    return false;
    }

版主解答:

“但是经常说==两边对象是按地址在比较,而equals()是按内容在比较”这句话在排除根类Object以及没有自己重写equals方法的情况下是对的。

即Object类中equals的实现就是用的==
其他继承Object的equals方法基本上都重写了这个方法,比如String类的equals方法:

XML/HTML code
 
?
1
2
3
4
5
6
7
8
9
10
11
12
equals
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. 
 
Overrides:
equals in class Object
Parameters:
anObject - The object to compare this String against 
Returns:
true if the given object represents a String equivalent to this string, false otherwise
See Also:
compareTo(String), equalsIgnoreCase(String)



这是String的equals方法源码:

Java code
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public boolean equals(Object obj)
    {
        if(this == obj)
            return true;
        if(obj instanceof String)
        {
            String s = (String)obj;
            int i = count;
            if(i == s.count)
            {
                char ac[] = value;
                char ac1[] = s.value;
                int j = offset;
                int k = s.offset;
                while(i-- != 0
                    if(ac[j++] != ac1[k++])
                        return false;
                return true;
            }
        }
        return false;
    }
原文地址:https://www.cnblogs.com/kenshinobiy/p/4652040.html