JAVA Collections

Collections静态类,提供了一些排序之类的方法:

测试类

package ds.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * Collections 排序
 * @author Hust
 * @Time 2011-11-9
 */
public class CollectionsTest {

	public static void main(String[] args) {
		copara();
	}
	
	public static void copara(){
		List<Po> pocs = new ArrayList<Po>();
		pocs.add(new Po(5));
		pocs.add(new Po(3));
		pocs.add(new Po(4));
		Iterator<Po> poit = pocs.iterator();
		while (poit.hasNext()) {
			Po po = (Po) poit.next();
			System.out.println(po.id);
		}
		/**
		 5,3,4
		 */
		System.out.println("内部类实现排序");		
		//排序对象
		Collections.sort(pocs, new Po.compareTo());
		Iterator<Po> poit2 = pocs.iterator();
		while (poit2.hasNext()) {
			Po po = (Po) poit2.next();
			System.out.println(po.id);
		}
		/**5,4,3*/
		
		System.out.println("实现接口完成排序");
		List<Po1> pocs2 = new ArrayList<Po1>();
		pocs2.add(new Po1(5));
		pocs2.add(new Po1(3));
		pocs2.add(new Po1(4));
		//排序对象
		Collections.sort(pocs2);
		Iterator<Po1> poit1 = pocs2.iterator();
		while (poit1.hasNext()) {
			Po1 po = (Po1) poit1.next();
			System.out.println(po.id);
		}
		/**3,4,5*/
		System.out.println("反转后");
		Collections.reverse(pocs2);
		Iterator<Po1> poitr = pocs2.iterator();
		while (poitr.hasNext()) {
			Po1 po = (Po1) poitr.next();
			System.out.println(po.id);
		}
		/** 5,4,3 */
		System.out.println("交换值后");
		Collections.swap(pocs2, 1, 2);
		Iterator<Po1> poitrs = pocs2.iterator();
		while (poitrs.hasNext()) {
			Po1 po = (Po1) poitrs.next();
			System.out.println(po.id);
		}
		/** 5,3,4 */
		
		System.out.println(Collections.max(pocs2).id); // 5
		System.out.println(Collections.min(pocs2).id); //3
		
	}
	
}

//实现coomparable接口
class Po1 implements Comparable<Po1>{

	int id ;
	
	public Po1(int id){
		this.id = id;
	}
	
	//从小到大
	@Override
	public int compareTo(Po1 o) {
		return (o.id<id)?1:(o.id == id)?0:-1;
	}
	
}

//测试对象 实现比较器接口
class Po {
	int id;
	Po(int id){
		this.id = id;
	}
	 
	 //静态内部类实现比较器接口    从大到小
	static class compareTo implements Comparator<Po> {
		@Override
		public int compare(Po o1, Po o2) {
			return (o1.id < o2.id)?1:(o1.id == o2.id)?0:-1;
		}		 
	}
}


 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值