实用的好东西比较器

    xiaoxiao2021-04-15  81

    把学生存入集合中,根据学生年龄从小到大排序

    package cn.huaxin.test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.TreeSet; public class Test2 implements Comparator<Student> { public int compare(Student o1, Student o2) { if (o1.age > o2.age) { return 1; } else if (o1.age < o2.age) { return -1; } else { return 0; } } public static void main(String[] args) { tes1(); TreeSet<Student> tree = new TreeSet(new Test2()); Student s1 = new Student(10,"小明"); tree.add(s1); Student s2 = new Student(5,"小红"); tree.add(s2); Student s3 = new Student(8,"小狗"); tree.add(s3); Student s4 = new Student(20,"小小"); tree.add(s4); Student s5 = new Student(200,"bu"); tree.add(s5); Student s6 = new Student(100,"aa"); tree.add(s6); Iterator<Student>it = tree.iterator(); while(it.hasNext()){ Student s = it.next(); System.out.println(s.name+"==年龄"+s.age); } } private static void tes1() { List<Student> list = new ArrayList<Student>(); Student s1 = new Student(10,"小"); Student s2 = new Student(5,"小明"); Student s3 = new Student(8,"小猫"); Student s4 = new Student(2,"小马"); list.add(s1); list.add(s2); list.add(s3); list.add(s4); Test2 com = new Test2(); Collections.sort(list, com); for(Student s : list){ System.out.println(); } } }
    转载请注明原文地址: https://ju.6miu.com/read-670877.html

    最新回复(0)