equals方法和“==”

在Object类中指示其他某个对象是否与此对象“相等”。 
            源代码:     
                    public boolean equals(Object obj) {
                            return (this == obj);
                    }

即此时的equals方法和==是相同的。

但是在字符串类型String类型中要注意源码中是将equals方法重写了。因此,此时的equals方法和==是不同的。

此时equals()方法是将字符串的内容作比较,而==是比较的对象是否是同一个对象。

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);//false
System.out.println(s1.equals(s2));//true

String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);//false
System.out.println(s3.equals(s4));//true

String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);//true
System.out.println(s5.equals(s6));//true

猜你喜欢

转载自blog.csdn.net/qq_34862798/article/details/81360197