Collections集合框架工具类

集合框架的工具类:
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;
	}

}

 

关注我的微信公众号(曲健磊的个人随笔),观看更多精彩内容:


 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值