java学习笔记:集合框架的工具类Collections

Collections:里面定义的都是一些操作collection对象的静态方法

List list=new ArrayList();

1.自然排序: Collections.sort(list);
2.倒序排序:Collections.sort(list,reverseOrder(new Comparator())); //比较器需要自己新建一个类,强行逆转一个比较器的顺序

3.max min

4.将非同步集合转成同步集合

CollectionsDemo

package com.Collections;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import com.Comparator.ComparatorBylength;

public class CollectionsDemo {

	public static void main(String[] args) {
		Collection<String> coll=new ArrayList<String>();
		coll.add("sad");
		coll.add("z");
		coll.add("b");
		String max=	getMax(coll);
		String max1=Collections.max(coll,new ComparatorBylength());
		
		System.out.println("max="+max);
		System.out.println("max1="+max1);
		
		//Collection中有一个可以将非同步集合转化为同步集合的方法
		// synchronized集合(非同步集合)
	}
	//模拟一个获取最大值的功能
	
	public static <T extends Object&Comparable<? super T>>T getMax(Collection<? extends T> coll) {
	
		Iterator<? extends T> it=coll.iterator();
		T max=it.next();
		//遍历元素
		while(it.hasNext()) {
			T temp=it.next();
		
		
		if(temp.compareTo(max)>0) {
			max=temp;
		}
		}
		return max;
		
	}
}


定义的比较器

package com.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、付费专栏及课程。

余额充值