本帖最后由 李慧声 于 2013-5-21 19:03 编辑
- class StudentDemo
- {
- public static void main(String[] args)
- {
- Set<Student> tr=new TreeSet<Student>(/*new MyComparator()*/);
- tr.add(new Student("孙三",18,87));
- tr.add(new Student("李四",19,86));
- tr.add(new Student("周五",18,77));
- tr.add(new Student("赵一",19,47));
- tr.add(new Student("钱二",18,85));
- for(Student s:tr)
- {
- System.out.println(s);
- }
- }
- }
- class MyComparator implements Comparator<Student> {
- public int compare(Student s1,Student s2) {
- if(s1.score > s2.score)
- return -1;
- else if(s1.score < s2.score)
- return 1;
- else
- return 0;
- }
- }
- class Student implements Comparable
- {
- public String name;
- public int age;
- public int score;
- Student(String name,int age,int score)
- {
- this.name=name;
- this.age=age;
- this.score=score;
- }
- @Override
- public String toString() {
- return "Student [name=" + name + ", age=" + age + ", score=" + score
- + "]";
- }
- @Override
- public int compareTo(Object obj) {
- if(obj instanceof Student) {
- Student stu = (Student)obj;
- if(this.score < stu.score)
- return 1;
- else if(this.score > stu.score)
- return -1;
- else
- return 0;
- }
- return 0;
- }
- }
复制代码 你的程序代码中错误比较多,拼写错误String s没有大写 Student s没有大写等等,成员引用错误,score不是方法,不能用score(),基础很重要哦。
比较有两种方法,自身实现Comparable,实现compareTo方法;另外一种另外写一个比较方法实现 Comparator<T>实现compare(T t1 ,T t2),这是我写的两种方法,你参考一下。
|