集合框架的工具类:
Collections:定义的都是操作Collection的静态方法。
1.对list排序
Collections.sort(list);
排序方法上泛型的由来。
class Student implements Comparable<Person>{
public int compareTo(Person p){
}
}
public static <T entends Comparable<? super T>> void sort(List<T> list){
}
public static void sort(List<Student> list){
stu1.compareTo(stu2);
}
2.逆序
Collections.reverseOrder();
3.max,min
Collections.max(coll);
4.二分查找
binarySearch(list,key);
5.将非同步集合转成同步集合
synchronizedList(List) 返回一个同步集合
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import cn.qujianlei.comparator.ComparatorByLength;
public class CollectionsDemo {
public static void main(String[] args) {
// methdoDemo1();
Collection<String> coll = new ArrayList<String>();
coll.add("a2333");
coll.add("aa");
coll.add("zzzz");
coll.add("nba");
String max = getMax(coll);
String max1 = Collections.max(coll,new ComparatorByLength());
System.out.println(max);
System.out.println(max1);
/*
* Collections中有一个可以将非同步集合转成同步集合的方法。
* synchronizedList,synchronizedCollection,synchronizedSet,synchronizedMap();
* 参数是一个非同步集合,返回一个同步集合
*/
}
/*
* 模拟一个获取集合最大值的功能
*/
public static<T extends Object & Comparable<? super T>> T getMax(Collection<? extends T> coll){
Iterator<? extends T> it = coll.iterator();
//1.定义变量记录容器中其中一个
T max = it.next();
//2.遍历容器所有的元素
while(it.hasNext()){
T temp = it.next();
//3.在遍历过程中进行比较,只要比变量中的值大,用变量记录下来,就哦了
if(temp.compareTo(max)>0){
max = temp;
}
}
return max;
}
public static void methdoDemo1(){
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("zkjifgfgf");
list.add("hehe");
list.add("nba");
System.out.println(list);
//对list排序,自然排序,使用的元素的compareTo方法
Collections.sort(list);
//按照长度排序(强行逆转)
Collections.sort(list, Collections.reverseOrder(new ComparatorByLength()));
//逆转自然排序(字典顺序)的排序方式
Collections.sort(list, Collections.reverseOrder());
//reverseOrder(Comparator) 强行逆转比较器的排序顺序,返回一个比较器
//reverseOrder() 强行逆转实现了Compareable接口的对象,collection的自然排序
System.out.println(list);
}
}
package cn.qujianlei.comparator;
import java.util.Comparator;
public class ComparatorByLength implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
int temp = o1.length()-o2.length();
return temp==0 ?o1.compareTo(o2):temp;
}
}
关注我的微信公众号(曲健磊的个人随笔),观看更多精彩内容: