String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); >>true
System.out.println(s1==s2); >>false
StringBuffer s3 = new StringBuffer("a");
StringBuffer s4 = new StringBuffer("a");
System.out.println(s3.equals(s4)); >>false
System.out.println(s3==s4); >>false
Student student = new Student("1", "haha");
Student student2 = new Student("1", "haha");
System.out.println(student.equals(student2));>>false
System.out.println(student==student2);>>false
System.out.println(student.name.equals(student2.name)); >>true
System.out.println(student.name==student2.name); >>true ???
总结:
对于字符串:equals()比较字符串的内容,“==”比较字符串内存的首地址。
对于非字符串:equals()和"=="都是比较对象在堆内存的首地址。
网友评论