A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© hadexs 中级黑马   /  2013-5-20 15:58  /  1011 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 刘胜寒 于 2013-5-23 20:06 编辑

定义一个学生类, 需要有姓名, 年龄, 考试成绩三个成员属性,创建5个对象, 属性可为任意值. 编程对这5个对象按成绩排序,并将结果输出。(提示,用TreeSet和Comparator实现)

评分

参与人数 1技术分 +1 收起 理由
Sword + 1

查看全部评分

1 个回复

倒序浏览
package com.sdtu.cn;

import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;
class  Student{
         String name;
         int age;
         float score;
        public Student(String name, int age, float score) {
                super();
                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 float getScore() {
                return score;
        }

        public void setScore(float score) {
                this.score = score;
        }

        @Override
        public String toString() {
                return "Student [name=" + name + ", age=" + age + ", score=" + score
                                + "]";
        }
         static class StudentCompare implements Comparator {

                @Override
                public int compare(Object o1, Object o2) {
                        Student s1 = (Student) o1;
                        Student s2 = (Student) o2;
                        int result = s1.score> s2.score?1:(s1.score==s2.score?0:-1);
                        if(result == 0){
                                result = s1.name.compareTo(s2.name);
                        }
                        return result;
                }
                 
         }
       
}
public class TreeSetTest {
        public static void main(String[]args){
        TreeSet ts = new TreeSet(new Student.StudentCompare());
        ts.add(new Student("老五",21,90));
        ts.add(new Student("老二",23,79));
        ts.add(new Student("老四",24,71));
        ts.add(new Student("老三",23,75));
        ts.add(new Student("老大",25,78));
        Iterator it = ts.iterator();
        while(it.hasNext()){
                System.out.println(it.next());
        }
        }
}

评分

参与人数 1技术分 +1 收起 理由
Sword + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马