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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. package com.review.demo2;

  2. import java.util.Comparator;
  3. import java.util.Iterator;
  4. import java.util.TreeSet;

  5. /**
  6. * 需求:向集合中添加学生对象,要求按照学生的年龄进行从小到大排序
  7. *         当年龄相同时在对姓名排序
  8. *
  9. */
  10. public class ConstraintDemo2 {

  11.         public static void main(String[] args) {
  12.                 // 创建集合对象,泛型约束存储Student对象,并指定比较器对象(用了匿名内部类)
  13.                 TreeSet<Student> set = new TreeSet<>(new Comparator<Student>(){
  14.                         public int compare(Student stu1,Student stu2){
  15.                                 int temp = stu1.getAge()-stu2.getAge();
  16.                                 //先比较年龄,年龄相同再比较姓名(compareTo方法在String类中重写的方法)
  17.                                 return temp==0?stu1.getName().compareTo(stu2.getName()):temp;
  18.                         }
  19.                 });
  20.                
  21.                 set.add(new Student("大vid",12));
  22.                 set.add(new Student("world",100));
  23.                 set.add(new Student("Africa",5550));
  24.                 for (Iterator<Student> it = set.iterator(); it.hasNext();) {
  25.                         Student student = it.next();
  26.                         System.out.println(student);
  27.                        
  28.                 }
  29.         }
  30. }
复制代码

0 个回复

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