- package com.review.demo2;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- /**
- * 需求:向集合中添加学生对象,要求按照学生的年龄进行从小到大排序
- * 当年龄相同时在对姓名排序
- *
- */
- public class ConstraintDemo2 {
- public static void main(String[] args) {
- // 创建集合对象,泛型约束存储Student对象,并指定比较器对象(用了匿名内部类)
- TreeSet<Student> set = new TreeSet<>(new Comparator<Student>(){
- public int compare(Student stu1,Student stu2){
- int temp = stu1.getAge()-stu2.getAge();
- //先比较年龄,年龄相同再比较姓名(compareTo方法在String类中重写的方法)
- return temp==0?stu1.getName().compareTo(stu2.getName()):temp;
- }
- });
-
- set.add(new Student("大vid",12));
- set.add(new Student("world",100));
- set.add(new Student("Africa",5550));
- for (Iterator<Student> it = set.iterator(); it.hasNext();) {
- Student student = it.next();
- System.out.println(student);
-
- }
- }
- }
复制代码 |
|