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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 编程小黑 中级黑马   /  2015-7-24 21:10  /  294 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文



import java.util.Set;
import java.util.TreeSet;

class Student implements Comparable{//必须实现接口
        private Integer age;

        public Student(Integer age) {
                super();
                this.age = age;
        }

        @Override
        public int compareTo(Object o) {//比较的规则,运用泛型可以消除强转!
                if(o instanceof Student){
                        Student s = (Student)o;
                        return this.age.compareTo(s.age);
                }
                return 0;
        }

        @Override
        public String toString() {
                return age+"" ;
        }
}

public class Demo14 {
        public static void main(String[] args) {
               
                Set<Student> s = new TreeSet();
                s.add(new Student(140));
                s.add(new Student(15));
                s.add(new Student(11));
                s.add(new Student(63));
                s.add(new Student(96));
                System.out.println(s);//[11, 15, 63, 96, 140]
        }
}

0 个回复

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