自定义一个比较器,对TreeSet 集合中的元素按指定方法来排序
import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; //自定义一个比较器 class Mycompare implements Comparator { @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub MinStudent ms1=(MinStudent )o1; MinStudent ms2=(MinStudent )o2; int i=ms1.getName().compareTo(ms2.getName()); if(i==0) return ms1.getAge()-ms2.getAge(); return i; } } public class MyCompareDemos { public static void main(String[] args) { // TODO Auto-generated method stub TreeSet ts = new TreeSet(new Mycompare()); ts.add(new MinStudent("ccc",22)); ts.add(new MinStudent("ddd",22)); ts.add(new MinStudent("aaa",21)); ts.add(new MinStudent("dad",23)); ts.add(new MinStudent("fff",25)); ts.add(new MinStudent("sss",22)); ts.add(new MinStudent("jjj",20)); Iterator it = ts.iterator(); while(it.hasNext()) { MinStudent ms = (MinStudent)it.next(); System.out.println(ms.toString()); } } }
class MinStudent implements Comparable { public int getName; private String name ; private int age; MinStudent(String name ,int age) { this.name = name ; this.age=age; } public int getAge() { return age; } public String getName() { return name; } public String toString() { return "name:"+name +" --- age"+age; } @Override public int compareTo(Object o) { // MinStudent s =(MinStudent) o; //先按照年龄排序 int i=this.getAge()-s.getAge(); if(i ==0) return this.getName().compareTo(s.getName()); return i; } }
未使用比较器前,集合中的元素顺序是》
使用比较器后:
时间: 2024-11-07 13:47:19