1. 程式人生 > >java學習筆記:集合框架的工具類Collections

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;
	}

}