74 lines
1.7 KiB
Java
74 lines
1.7 KiB
Java
package chapter6;
|
||
|
||
import java.util.HashSet;
|
||
import java.util.Iterator;
|
||
|
||
class Student implements Comparable<Student> {
|
||
String id;
|
||
String name;
|
||
int height;
|
||
|
||
public Student(String id, String name) {
|
||
this.id = id;
|
||
this.name = name;
|
||
}
|
||
|
||
public void setHeight(int height) {
|
||
this.height = height;
|
||
}
|
||
|
||
public String toString() {
|
||
return id + ":" + name;
|
||
}
|
||
|
||
public int hashCode() {
|
||
return id.hashCode();
|
||
}
|
||
|
||
public boolean equals(Object obj) {
|
||
if (this == obj) {
|
||
return true;
|
||
}
|
||
|
||
if (!(obj instanceof Student)) {
|
||
return false;
|
||
}
|
||
|
||
Student other = (Student) obj;
|
||
return this.id.equals(other.id);
|
||
}
|
||
|
||
public int compareTo(Student other) {
|
||
if (this.height > other.height) {
|
||
return 1; // 返回正数:表示"我"比"你"大
|
||
} else if (this.height < other.height) {
|
||
return -1; // 返回负数:表示"我"比"你"小
|
||
} else {
|
||
return 0; // 返回0:表示"我"和"你"一样大
|
||
}
|
||
}
|
||
}
|
||
|
||
public class Example08 {
|
||
public static void main(String[] args) {
|
||
HashSet<Student> students = new HashSet<>();
|
||
|
||
Student s1 = new Student("1", "张三");
|
||
Student s2 = new Student("2", "李四");
|
||
Student s3 = new Student("2", "李四");
|
||
Student s4 = new Student("3", "王五");
|
||
|
||
students.add(s3);
|
||
students.add(s4);
|
||
students.add(s1);
|
||
students.add(s2);
|
||
|
||
Iterator<Student> iterator = students.iterator();
|
||
while (iterator.hasNext()) {
|
||
Student student = iterator.next();
|
||
System.out.println(student);
|
||
}
|
||
|
||
}
|
||
}
|