Collections-sort

2018-09-22  本文已影响0人  东风谷123Liter
class Student04 implements Person04{ 
}
list.add(new Student04);
public static <T extends Comparator<? super T>> void sort(List<T> list) {
     //讲解:泛型T必须是Comparator的子类,
     //后面Comparator的参数用的泛型表示Comparator允许接受T的父类;
     //例如,这里传过来的T就是Student04类型,那么传Personal04类型也是一样可以的。
}
import java.util.*;
public class sortDemo {
     public static void main(String[] args) {
           List<String> li = new ArrayList<String>();
           li.add("abcd");
           li.add("llbc");
           li.add("dddddd");
           li.add("kl");
           sop(li);
           Collections.sort(li);
           sop(li);    
     }
     public static void sop(Object obj) {
           System.out.println(obj);
     }
}
//定义一个比较器,使其依据字符长度进行排序;
class stringLengthComparator implements Comparator<String>{
     public int compare(String st1, String st2) {
           if(st1.length()>st2.length())
                return 1;
           if(st1.length()==st2.length())
                return st1.compareTo(st2);
           return -1;
     }
}
Collections.sort(li, new stringLengthComparator());
sop("未排序前  "+li);
           Collections.sort(li);
           sop("自然排序后  "+li);
           Collections.sort(li, new stringLengthComparator());
           sop("字符串长度排序后  "+li);
           String stm = Collections.max(li);
           sop("自然顺序取最大值 "+stm);
           String stc = Collections.max(li, new stringLengthComparator());
           sop("字符串长度排序取最大值 "+stc);
上一篇 下一篇

猜你喜欢

热点阅读