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

a
  1. package treesetdemo;
  2. /**
  3. * 定义学生对象,其可进行年龄大小的比较,所以需要实现Comparable接口
  4. * */
  5. public class Student implements Comparable<Student>{
  6.         private String name;
  7.         private int age;
  8.         public Student(String name, int age) {
  9.                 super();
  10.                 this.name = name;
  11.                 this.age = age;
  12.         }
  13.         public String getName() {
  14.                 return name;
  15.         }
  16.         public void setName(String name) {
  17.                 this.name = name;
  18.         }
  19.         public int getAge() {
  20.                 return age;
  21.         }
  22.         public void setAge(int age) {
  23.                 this.age = age;
  24.         }
  25.         //复写Comparable中的compareTo方法
  26.         //返回正数则是自然升序   负数为 降序   0 则认为是是同一元素
  27.         @Override
  28.         public int compareTo(Student o) {
  29.                 // TODO Auto-generated method stub
  30.                 int result = this.age - o.age;  //比较年龄大小
  31.                 if(result == 0){
  32.                         result = this.name.compareTo(o.name);//当年龄相同时,按姓名自然排序排
  33.                 }
  34.                 return result;
  35.         }
  36.        
  37.        
  38. }
  39. package treesetdemo;

  40. import java.util.TreeSet;

  41. public class TreeSetDemo1 {

  42.         /**
  43.          * 需求:存储自定义的学生对象,并保证元素的唯一性,并按照年龄从小到大排序
  44.          */
  45.         public static void main(String[] args) {
  46.                 // TODO Auto-generated method stub
  47.                 //建立TreeSet
  48.                 TreeSet<Student> ts = new TreeSet<Student>();
  49.                 //建立学生对象
  50.                 Student s1 = new Student("uiui",18);
  51.                 Student s2 = new Student("haha",22);
  52.                 Student s3 = new Student("gege",12);
  53.                 Student s4 = new Student("Lili",18);
  54.                 Student s5 = new Student("Licu",13);
  55.                 Student s6 = new Student("Lili",18);
  56.                 //添加对象
  57.                 ts.add(s1);
  58.                 ts.add(s2);
  59.                 ts.add(s3);
  60.                 ts.add(s4);
  61.                 ts.add(s5);
  62.                 ts.add(s6);
  63.                 //遍历集合
  64.                 for(Student s: ts){
  65.                         System.out.println(s.getName()+"..."+s.getAge());
  66.                 }
  67.         }

  68. }
复制代码


1 个回复

倒序浏览
输出
gege...12
Licu...13
Lili...18
uiui...18
haha...22
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马