美文网首页
Collections-sort

Collections-sort

作者: 东风谷123Liter | 来源:发表于2018-09-22 09:46 被阅读0次
  • 现在有一堆元素,不需要保证数据的唯一性,所以我们不用HashSet,同时我们有要求对这对数据进行排序;所以我们就不能选择HashMap,那就用List,如果要对List进行排序,那就要调用Collectios中的sort方法。
  • sort方法的原理:
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());
  • 结果:
  • MAX方法:

    可知他有2个方法,一个是根据自然排序,选出最大的值;另一个是调用Comparator接口,自定排序方式选出最大值;

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);
  • 结果:

相关文章

  • Collections-sort

    现在有一堆元素,不需要保证数据的唯一性,所以我们不用HashSet,同时我们有要求对这对数据进行排序;所以我们就不...

  • Java基础day17笔记:Collecitons-sort/m

    10-集合(Collections-sort) 集合框架我们基本都讲完了,就剩下了这一部分,工具类: ...

网友评论

      本文标题:Collections-sort

      本文链接:https://www.haomeiwen.com/subject/lavtoftx.html