Set operation -- custom comparable comparer

From , 4 Years ago, written in Java, viewed 52 times.
URL https://pastebin.vip/view/535ab766
  1. 1.
  2. package s0223排序比较器_推荐使用comparator;
  3. //排序比较的2种实现方法
  4. //1. 实体类                                 java.lang.Comparable Comparato
  5. //2.自定义比较器,implements java.util.Comparator,然后重写compare()方法
  6. public class Comparator1 implements java.util.Comparator<String> {
  7.  
  8.  
  9.         public int compare(String o1, String o2) {
  10.       int len1=o1.length();
  11.       int len2=o2.length();
  12.                 return len1-len2;
  13.         }
  14.  
  15.  
  16.  
  17. }
  18.  
  19. 2.
  20. package s0223排序比较器_推荐使用comparator;
  21.  
  22. import java.util.Arrays;
  23. import java.util.Collections;
  24. import java.util.List;
  25.  
  26. public class Main {
  27.  
  28.         public static void  main(String [] args){
  29.  
  30.     String[] str={"a","abcd","abc","def"};
  31.     List<String> list=Arrays.asList(str);
  32.     System.out.println("排序前:"+list);
  33.  
  34. //    Collections.sort(list);
  35.     Collections.sort(list,new Comparator1());//对指定列表排序,使用指定比较器 ,这里是从小到大排序
  36.     System.out.println("排序后"+list);
  37.         }
  38.  
  39. }
  40.  

Reply to "Set operation -- custom comparable comparer"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website