Java面试题:==和equals的比较

==和equals比较

==对比的是栈中的值,基本数据类型是变量值,引用类型是堆中内存对象的地址

equals: object中默认也是采用==比较,通常会重写

Object

public boolean equals(Object obj){
    return (this == obj);
}

String

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;
}

上述代码可以看出,String类中被复写的equals()方法其实是比较两个字符串的内容。

public class StringDemo{
    public static void main(String[] args) {
        //在常量池中分配内存
        String str1 = "Hello"; 
        //在堆中分配内存
        String str2 = new String("Hello");
        String str3 = str2;
        System.out.println(str1 == str2);
        System.out.println(str1 == str3);
        System.out.println(str2 == str3);
        System.out.println(str1.equals(str2));
        System.out.println(str1.equals(str3));
        System.out.println(str2.equals(str3));
    }
}

你可能感兴趣的:(Java面试题笔记)