1 package com.jdk7.chapter4; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.List; 7 8 public class MyComparator implements Comparator { 9 10 /** 11 * o1<o2 return 1; 12 * o1=o2 return 0; 13 * o1>o2 return -1; 14 * 比较结果为1才是符合自定义排序的 15 */ 16 @Override 17 public int compare(Object o1, Object o2) { 18 int num1 = ((Integer)o1).intValue(); 19 int num2 = ((Integer)o2).intValue(); 20 if(num1 < num2){ 21 return 1; 22 }else if(num1 == num2){ 23 return 0; 24 } 25 return -1; 26 } 27 28 public void printArray(List list){ 29 if(list==null){ 30 System.out.println("列表为空无法排序!"); 31 } 32 System.out.print("队列展示为: "); 33 for(int i=0;i<list.size();i++){ 34 System.out.print(list.get(i)+" "); 35 } 36 System.out.println(); 37 } 38 39 public static void main(String[] args) { 40 MyComparator myComparator = new MyComparator(); 41 List list = new ArrayList(); 42 list.add(1); 43 list.add(4); 44 list.add(2); 45 list.add(6); 46 list.add(9); 47 list.add(8); 48 System.out.println("默认排序后的队列展示为:"); 49 Collections.sort(list); 50 myComparator.printArray(list); 51 System.out.println("自定义排序后的队列展示为:"); 52 Collections.sort(list, myComparator); 53 myComparator.printArray(list); 54 } 55 56 } 57 58 执行结果: 59 默认排序后的队列展示为: 60 队列展示为: 1 2 4 6 8 9 61 自定义排序后的队列展示为: 62 队列展示为: 9 8 6 4 2 1
原文地址:https://www.cnblogs.com/celine/p/8456836.html
时间: 2024-10-11 22:33:44