- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- public class Test2 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TreeSet<Student> ts=new TreeSet<Student>(new MyComp());
- ts.add(new Student("张三",21, 56));
- ts.add(new Student("王五",22, 57));
- ts.add(new Student("李四",23, 55));
- ts.add(new Student("赵六",24, 53));
- ts.add(new Student("马斯",25, 50));
-
-
-
- for(Iterator<Student> set=ts.iterator();set.hasNext();)
- {
- Student stu=set.next();
- System.out.println(stu.getName()+"..."+stu.getScore());
- }
-
- }
- }
- class Student{
- private String name;
- private int age;
- private int score;
- public Student(String name, int age, int score) {
- this.name = name;
- this.age = age;
- this.score = score;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getScore() {
- return score;
- }
- public void setScore(int score) {
- this.score = score;
- }
- @Override
- public boolean equals(Object arg0) {
- // TODO Auto-generated method stub
- if(!(arg0 instanceof Student))
- throw new ClassCastException("不是student类型");
- Student stu=(Student)arg0;
- return this.name.equals(stu.name)&&this.age==stu.age&&this.score==stu.score;
- }
- @Override
- public int hashCode() {
- // TODO Auto-generated method stub
- return this.name.hashCode()+this.age*13;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "姓名:"+this.name+" 年龄:"+this.age+" 得分:"+this.score;
- }
- }
- class MyComp implements Comparator<Student>{
- @Override
- public int compare(Student arg0, Student arg1) {
- // TODO Auto-generated method stub
- return new Integer(arg0.getScore()).compareTo(arg1.getScore());//从低到高
复制代码
|
|