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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© linder_qzy 中级黑马   /  2015-3-4 15:21  /  640 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)
下边是我写的,想问下用TreeSet该怎么写
package com.itheima;


import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
class Test10 {
        public static void main(String[] args) {
                TreeMap<Student, String> tm = new TreeMap<Student, String>();
                //将学生对象放入TreeMap中
                tm.put(new Student("张三", 21, 98), "1");
                tm.put(new Student("李四", 22, 85), "2");
                tm.put(new Student("王五", 23, 88), "3");
                tm.put(new Student("赵六", 21, 76), "4");
                tm.put(new Student("陈七", 22, 90), "5");
                Set<Map.Entry<Student, String>> entrySet = tm.entrySet();
                Iterator<Map.Entry<Student, String>> iter = entrySet.iterator();
                while (iter.hasNext()) {
                        Map.Entry<Student, String> me = iter.next();
                        Student s = me.getKey();
                        String add_r = me.getValue();
                        System.out.println(s);
                }
        }
}


class Student implements Comparable<Student> {


        private String name;
        private int age;
        private int score;


        Student(String name, int age, int score) {
                this.name = name;
                this.age = age;
                this.score = score;
        }


        // 重写hashCode()和equals()方法为了保证对象的唯一性
        public int hashCode() {
                return name.hashCode() + age * 34;
        }


        public boolean equals(Object obj) {
                if (!(obj instanceof Student))
                        throw new RuntimeException("类型不匹配");
                Student s = (Student) obj;
                return this.name.equals(s.name) && this.age == s.age
                                && this.score == s.score;
        }


        // 重写compareTo方法(存入二叉树结构集合必备)
        public int compareTo(Student s) {
                int num = new Integer(this.score).compareTo(new Integer(s.score));
                if (num == 0)
                        return this.name.compareTo(s.name);
                return num;
        }


        public int getAge() {
                return age;
        }


        public String getName() {
                return name;
        }


        public int getScore() {
                return score;
        }


        public String toString() {
                return "姓名:" + name + ",年龄:" + age + ",分数:" + score;
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马