public boolean equals(Object o) {
//this --- s1
//o ---s2
if (this == o) return true;
//getClass() != o.getClass() 判断两个对象是否来自同一个类
if (o == null || getClass() != o.getClass()) return false;
//向下转型
Student student = (Student) o;
if (age != student.age) return false;
//name.equals(student.name)相同 返回true
return name != null ? name.equals(student.name) : student.name == null;
}
String的equals方法因为重写了Object的equals方法,所以可以比较字符串的内容,而StringBuffer因为没重写equals方法,直接继承了Object的equals方法,所以不行。
那么如何比较StringBuffer字符串内容是否相等呢?
可以使用toString() 方法将StringBuffer的内容转换为String 字符串,再使用equals()方法比较。