1.equals方法
java经常会涉及到类对象之间的equals比较问题,默认情况,equals方法比较的都是两者的地址,比如我们自定义了一个Student类:
public class Student {
private String name;
private String sno;
public Student(String name, String sno) {
this.name = name;
this.sno = sno;
}
}
然后我们在测试类中去使用它:
public class test {
public static void main(String[] args) {
Student student1 = new Student("Jerry", "1011");
Student student2 = new Student("Jerry", "1011");
System.out.println(student1.equals(student2));
}
}
此时运行结果为false,但是这与常识相反,明明都是名字为Jerry,学号为1011的学生,但是判断结果却为false,所以此时需要重写Student类中的equals方法,不让它进行地址比较。
public class Student {
private String name;
private String sno;
public Student(String name, String sno) {
this.name = name;
this.sno = sno;
}
@Override
public boolean equals(Object student) {
if (this == student)
return true;
if (this == null || this.getClass() != student.getClass())
return false;
Student sto = (Student) student;
return this.name.equals(sto.name) && this.sno.equals(sto.sno);
}
}
为了确保方法安全,equals方法的前面需要加上判断,判断的内容是:
- 传入的参数如果就是该对象自己,则返回true(自己和自己比较当然相等)
- 传入的参数为空,则返回false
- 传入的参数并不是一个Student类,则返回false
这三个判断逻辑是固定写法,记住即可!
2.compareTo方法
有时候需要根据自定义类的某个属性进行比较,此时就需要实现Comparable接口,然后重写compareTo方法。如果compareTo返回值大于0:this.score>o.score
如果compareTo返回值等于0:this.score=o.score
如果compareTo返回值小于0:this.score<o.score
public class Student implements Comparable<Student> {
private String name;
private String sno;
private int score;
public Student(String name, String sno, int score) {
this.name = name;
this.sno = sno;
this.score = score;
}
@Override
public int compareTo(Student o) {
return this.score - o.score;
}
}