请问,在集合HashSet中,多个对象的成员排序问题

不知该叫什么 2014-03-28 12:10:52
把多个学生放进一个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());
}
}

虽然出现的结果有一定的顺序,但是不知道用什么方法能使得结果按照要求排序,初学者请教 谢谢!。
...全文
273 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuebichongkafei 2014-03-28
  • 打赏
  • 举报
回复
else if条件语句else if (st1.equals(st2) == false && st1.equals(st3)&& st2.equals(st3)) 只有在真的情况下能够进入,按照你的表达式是一直进不了else if代码段当中的!&&是短路与,只要前面是假后面就不会进行计算了
harrisonkao 2014-03-28
  • 打赏
  • 举报
回复
hash 是无序的集合
代码间的舞者 2014-03-28
  • 打赏
  • 举报
回复
1、楼主的这段代码没有比较大小的方法,so 肯定不能满足你的要求。 2、若想要排序输出,建议重写hashCode的方法
haorengoodman 2014-03-28
  • 打赏
  • 举报
回复
只用按照要求重写equals方法就OK
不知该叫什么 2014-03-28
  • 打赏
  • 举报
回复
引用 3 楼 xuebichongkafei 的回复:
else if条件语句else if (st1.equals(st2) == false && st1.equals(st3)&& st2.equals(st3)) 只有在真的情况下能够进入,按照你的表达式是一直进不了else if代码段当中的!&&是短路与,只要前面是假后面就不会进行计算了
前面是假的时候就可以直接进去啊,没问题的
S117 2014-03-28
  • 打赏
  • 举报
回复
使用TreeSet,再自己写个Comparator比较器!
qunhao 2014-03-28
  • 打赏
  • 举报
回复
请用TreeSet。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧