请问,在集合HashSet中,多个对象的成员排序问题
把多个学生放进一个HashSet集合,实现先按学生的成绩,若成绩相等再按年龄排序
package lianxi;
import java.util.HashSet;
import java.util.Set;
class Student {
private long id;
private String name;
private int age;
private int score;
public Student(int score, int age, long id, String name) {
this.id = id;
this.name = name;
this.age = age;
this.score = score;
}
/*
* public Integer getScore() { return score; }
*
* public Integer getAge() { return age; }
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + score;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (score != other.score)
return false;
return true;
}
public String toString() {
return "ID:" + id + " Name:" + name + " Age:" + age + " Score:" + score;
}
}
public class HashSetStudent {
public static void main(String[] args) {
Student st1 = new Student(88, 20, 122180505, "Tom");
Student st2 = new Student(89, 23, 122180508, "Lucy");
Student st3 = new Student(89, 22, 122180532, "Frank");
// Student st3=new Student(89,23,122180508, "Lucy" );
Set StudentSet = new HashSet();
if (st1.hashCode() != st2.hashCode()
&& st1.hashCode() != st3.hashCode()
&& st3.hashCode() != st2.hashCode()) {
System.out.println("元素添加进去");
StudentSet.add(st1);
StudentSet.add(st2);
StudentSet.add(st3);
} else if (st1.equals(st2) == false && st1.equals(st3)
&& st2.equals(st3)) {
System.out.println("元素的hashcode值相等,但equal不相等的情况下,元素添加");
StudentSet.add(st1);
StudentSet.add(st2);
StudentSet.add(st3);
} else {
System.out.println("这两个元素完全相等,不能放在同一个集合中");
}
System.out.println(StudentSet.toString());
}
}
虽然出现的结果有一定的顺序,但是不知道用什么方法能使得结果按照要求排序,初学者请教 谢谢!。