java学习-使用sort()对ArrayList进行排序

出自:https://blog.csdn.net/tuolaji8/article/details/48418711

java中的ArrayList需要通过collections类的sort方法来进行排序

如果想自定义排序方式则需要有类来实现Comparator接口并重写compare方法

调用sort方法时将ArrayList对象与实现Commparator接口的类的对象作为参数



举个例子:
[java]  view plain  copy
  1. package book.arrayset;  
  2.   
  3. import java.util.Comparator;  
  4.   
  5. /** 
  6. * 整数比较器,将整数按降序排列 
  7. */  
  8. class MyIntComparator implements Comparator{  
  9.   
  10. /** 
  11. * o1比o2大,返回-1;o1比o2小,返回1。 
  12. */  
  13. public int compare(Object o1, Object o2) {  
  14. int i1 = ((Integer)o1).intValue();  
  15. int i2 = ((Integer)o2).intValue();  
  16. if (i1 < i2){  
  17. return 1;  
  18. }  
  19. if (i1 > i2){  
  20. return -1;  
  21. }  
  22. return 0;  
  23. }  
  24. }  
  25.   
  26. //上面的为比较的函数实现,下面真正的添加数据,  
  27.   
  28. //通过调用上面的比较函数实现自定义排序的功能  
  29.   
  30. package book.arrayset;  
  31.   
  32. import java.util.ArrayList;  
  33. import java.util.Collections;  
  34. import java.util.List;  
  35.   
  36. /** 
  37. * 对List中的元素排序 
  38. */  
  39. public class SortList {  
  40.   
  41. public static void output(List list){  
  42. if (list == null){  
  43. return;  
  44. }  
  45. for (int i=0; i<list.size(); i++){  
  46. System.out.print(list.get(i).toString() + " ");  
  47. }  
  48. System.out.println();  
  49. }  
  50.   
  51. public static void main(String[] args) {  
  52. List list = new ArrayList();  
  53. list.add(new Integer(5));  
  54. list.add(new Integer(8));  
  55. list.add(new Integer(1));  
  56. list.add(new Integer(3));  
  57. list.add(new Integer(2));  
  58. list.add(new Double(3.1));  
[java]  view plain  copy
  1. <span style="font-family: Arial, Helvetica, sans-serif;">System.out.println("list开始状态");</span>  
[java]  view plain  copy
  1. SortList.output(list);  
[java]  view plain  copy
  1. //Collections.sort  <span style="color:#ff0000;">用默认比较器排列list的元素</span>  
  2. Collections.sort(list);  
  3. System.out.println("list被默认比较器排序后的状态");  
  4. SortList.output(list);  
[java]  view plain  copy
  1. //用自定义方法按降序排列</span>  
  2. Collections.sort(list, new MyIntComparator());  
  3. System.out.println("list被自定义比较器排序后的状态");  
  4. SortList.output(list);  
  5.   
  6.   
  7. }  
  8. }  
[java]  view plain  copy
  1.   
[java]  view plain  copy
  1. 因此,对于任意自定义类的对象,当保存在集合类容器中后,如果需要对它们进行排序,需要自己提供适应于自定义类的比较器,自定义比较器必须实现Comparator接口。然后采用Collections.sort(list, comparator);方法对容器进行排序。</span>  

猜你喜欢

转载自blog.csdn.net/kangkang_hacker/article/details/80754711
今日推荐