/*
*集合框架的工具类
*Collections
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class CollectionsDemo {
public static void main(String[] args) {
sortDemo();
System.out.println();
binarySearshDemo();
}
public static void binarySearshDemo(){
ArrayList<String> list=new ArrayList<String>();
list.add("asdas");
list.add("rtr");
list.add("hh");
list.add("hh");
list.add("aa");
list.add("asdadcsdfs");
list.add("ujuku");
Collections.sort(list);
sop(list);
//必须要先排序,才能使用binarySearch方法
int index=Collections.binarySearch(list, "rtrq");
int index1=halfSearch(list,"rtrq");
sop("index:"+index);
sop("index1:"+index1);
}
//binarySearch方法的原理
public static int halfSearch(ArrayList<String> list,String key){
int max,min,mid;
max=list.size()-1;
min=0;
while(min<=max)
{
mid=(min+max)>>1; // /2;
String str=list.get(mid);
int num=str.compareTo(key);
if(num>0)
max=mid-1;
else if(num<0)
min=mid+1;
else
return mid;
}
return -min-1;
}
//比较器原理(如果元素自身不具备比较器,就要自定义一个比较器)
public static int halfSearch2(ArrayList<String> list,String key,Comparator<String> cmp){
int max,min,mid;
max=list.size()-1;
min=0;
while(min<=max)
{
mid=(min+max)>>1; // /2;
String str=list.get(mid);
int num=cmp.compare(str,key);
if(num>0)
max=mid-1;
else if(num<0)
min=mid+1;
else
return mid;
}
return -min-1;
}
public static void sortDemo(){
ArrayList<String> list=new ArrayList<String>();
list.add("asdas");
list.add("rtr");
list.add("hh");
list.add("hh");
list.add("aa");
list.add("asdadcsdfs");
list.add("ujuku");
sop("排序前:");
sop(list);
Collections.sort(list);
sop("自然排序的结果:");
sop(list);
//int index=halfSearch2(list,"aa",new StrLenComparator());
Collections.sort(list,new StrLenComparator());
sop("按照长度排序:");
sop(list);
//sop(index);
String valuemax=Collections.max(list);
sop("valuemax:"+valuemax);
String lenmax=Collections.max(list,new StrLenComparator());
sop("Lenmax:"+lenmax);
}
public static void sop(Object obj){
System.out.println(obj);
}
}
class StrLenComparator implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
// TODO 自动生成的方法存根
if(s1.length()>s2.length())
return 1;
if(s1.length()<s2.length())
return -1;
return s1.compareTo(s2);
}
}
结果图: