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