日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Java TreeSet的定制排序

發(fā)布時間:2025/3/20 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java TreeSet的定制排序 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

注:只貼出實現(xiàn)類

package Test3;

import java.util.Comparator;
import java.util.TreeSet;

public class Test {

public static void main(String[] args) {
Comparator com=new Comparator() {①創(chuàng)建一個Comparator接口的匿名內(nèi)部類

@Override
public int compare(Object o1, Object o2) {②重寫compare方法,定制排序的方法
if(o1 instanceof Employee && o2 instanceof Employee){
Employee e1=(Employee)o1;
Employee e2=(Employee)o2;
MyDate birth1=e1.getBirthday();
MyDate birth2=e2.getBirthday();
if(birth1.getYear()!=birth2.getYear()){
return birth1.getYear()-birth2.getYear();
}else{
if(birth1.getMonth()!=birth2.getMonth()){
return birth1.getMonth()-birth2.getMonth();
}else{
if(birth1.getDay()!=birth2.getDay()){
return birth1.getDay()-birth2.getDay();
}
}
}
}
return 0;
}

};
Employee e1=new Employee("胡",23,new MyDate(1992,10,27));
Employee e2=new Employee("趙",19,new MyDate(1996,10,27));
Employee e3=new Employee("錢",21,new MyDate(1994,10,27));
Employee e4=new Employee("孫",22,new MyDate(1993,10,27));
Employee e5=new Employee("李",20,new MyDate(1995,10,27));

TreeSet<Employee> set=new TreeSet<Employee>(com);③把實現(xiàn)Comparator接口的對象傳遞到TreeSet構(gòu)造器
set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);

for(Employee e:set){
System.out.println(e);
}
}
}

轉(zhuǎn)載于:https://www.cnblogs.com/BlogRegisterboby/p/5907622.html

總結(jié)

以上是生活随笔為你收集整理的Java TreeSet的定制排序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。