1. 程式人生 > 其它 >集合框架-工具類-Collections-折半最值

集合框架-工具類-Collections-折半最值

 1 package cn.itcast.p2.toolclass.collections.demo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 import java.util.List;
 7 
 8 import cn.itcast.p2.comparator.ComparatorByLength;
 9 
10 public class CollectionsDemo {
11 
12     public static void
main(String[] args) { 13 // TODO Auto-generated method stub 14 /* 15 * Collections:是集合框架的工具類。 16 * 裡面的方法都是靜態的。 17 */ 18 // demo_1(); 19 demo_2(); 20 21 } 22 23 private static void demo_2() { 24 // TODO Auto-generated method stub
25 List<String> list = new ArrayList<String>(); 26 27 list.add("abcde"); 28 list.add("cba"); 29 list.add("aa"); 30 list.add("zzz"); 31 list.add("cba"); 32 list.add("nbaa"); 33 //折半要先排序 34 Collections.sort(list);
35 System.out.println(list); 36 37 int index = Collections.binarySearch(list, "aaa"); 38 39 System.out.println("index="+index); 40 41 //獲取最大值。 42 // String max = Collections.max(list);//max=zzz 43 String max = Collections.max(list,new ComparatorByLength()); 44 System.out.println("max="+max); 45 }
CollectionsDemo
 1 package cn.itcast.p2.comparator;
 2 
 3 import java.util.Comparator;
 4 
 5 public class ComparatorByLength implements Comparator<String> {
 6 
 7     @Override
 8     public int compare(String o1, String o2) {
 9         // TODO Auto-generated method stub
10         int temp = o1.length()-o2.length();
11         
12         return temp==0?o1.compareTo(o2):temp;
13     }
14 
15 }
ComparatorByLength