Java 默认的equals只能比较同类型的object,一旦比较对象类型不同就会报错。下面是当类型不同时返回false避免报错的方法。
Example:
public class Student implements Comparable<Student> {
private String name;
private int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "Name: " + name + ", Id: " + id;
}
public int compareTo(Student other) {
if (id < other.id) {
return -1;
} else if (id == other.id) {
return 0;
} else {
return 1;
}
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Student)) {
return false;
} else {
return compareTo((Student) obj) == 0;
}
}
/* If we override equals we must have correct hashCode */
public int hashCode() {
return id;
}
}
Driver:import java.util.ArrayList;
import java.util.Collections;
public class Driver {
public static void main(String[] args) {
ArrayList<Student> roster = new ArrayList<Student>();
roster.add(new Student("Mary", 10));
roster.add(new Student("Bob", 1));
roster.add(new Student("Laura", 17));
roster.add(new Student("Albert", 34));
/* Collection is sorted by id */
Collections.sort(roster);
for (Student s : roster) {
System.out.println(s);
}
/* equals method tests */
Student s1 = new Student("John", 10);
Student s2 = new Student("John", 10);
Student s3 = new Student("Mary", 20);
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s1));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(null));
}
}
输出为:Name: Bob, Id: 1
Name: Mary, Id: 10
Name: Laura, Id: 17
Name: Albert, Id: 34
true
true
false
false