java基础入门----Collections1 集合框架工具类

时间:2023-02-24 23:21:02
import java.util.*;

class Collections1 //集合框架工具类
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
//sortDemo(); //排序方法
//maxDemo();//取最大就是去排序完后最后的元素
//binarySearchDemo(); //折半查找
/*
List<String> list = new ArrayList<String>();
list.add("asdf");
list.add("ed");
list.add("vfvf");
list.add("addee");
Collections.sort(list);
sop(list);
sop(halfSearchDemo(list,"ed"));

Collections.sort(list,new StrLennComparator());
sop(list);
sop(halfSearchDemo2(list,"ed",new StrLennComparator()));
*/
}
public static void sortDemo()
{
List<String> list = new ArrayList<String>();

list.add("asdf");
list.add("ed");
list.add("vfvf");
list.add("addee");

Collections.sort(list);
sop(list);

Collections.sort(list,new StrLennComparator());
sop(list);
}
public static void maxDemo()
{
List<String> list = new ArrayList<String>();
list.add("asdf");
list.add("ed");
list.add("vfvf");
list.add("addee");
Collections.sort(list);
sop(list);
sop(Collections.max(list));

Collections.sort(list,new StrLennComparator());
sop(list);
sop(Collections.max(list,new StrLennComparator()));
}
public static void binarySearchDemo()
{
List<String> list = new ArrayList<String>();
list.add("asdf");
list.add("ed");
list.add("vfvf");
list.add("addee");
Collections.sort(list);//Collections.sort(list,new StrLennComparator());
sop(list);

int index = Collections.binarySearch(list, "vfvf"/*,new StrLennComparator()*/);
sop("index="+index);
}
public static int halfSearchDemo(List<String> list, String key)//二半查找原理
{
int max,min,mid;
max = list.size()-1;
min = 0;

while(min <= max)
{
mid = (max+min)/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 halfSearchDemo2(List<String> list, String key,Comparator<String> cmp)
{
int max,min,mid;
max = list.size()-1;
min = 0;

while(min <= max)
{
mid = (max+min)/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;
}
}

class StrLennComparator implements Comparator<String>
{
public int compare(String s1, String s2)
{
if(s1.length() > s2.length())
return 1;
if(s1.length() < s2.length())
return -1;
return s1.compareTo(s2);
}
}