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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

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

实现Comparable接口后边为什么要加泛型<Student>
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 个回复

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