您的位置:首页 > 移动开发 > Objective-C

Java 将equals override为比较所有object的方法

2017-12-29 13:00 483 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java basic equals