黑马程序员技术交流社区

标题: TreeSet的自然排序,升序 [打印本页]

作者: 编程小黑    时间: 2015-7-24 21:10
标题: TreeSet的自然排序,升序


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]
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2