导入:
大家有没有遇到自定义的类,无法用equals方法比较成员属性呀?那是因为需要重写equals方法
重写原理这里偷个懒,idea中 alt+insert 快捷键,快速实现重写equals噢!
Student类:
package objectequal;
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
测试类:
package objectequal;
public class Test {
public static void main(String[] args) {
Student s1 = new Student("wxw",22);
Student s2 = new Student("wxw",22);
String s3="wwx";
String s4="wwx";
System.out.println("String类型的可用equals比较,相同返回true,不同返回false");
System.out.println("s3.equals(s4)):"+s3.equals(s4));
System.out.println("自定义的Student类,无法使用equals比较");
System.out.println("s1.equals(s2):"+s1.equals(s2));
}
}
重写equals后的Student类:
package objectequal;
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}
重写equals后,可以比较Student类的成员属性