日期:2014-05-20 浏览次数:20772 次
import java.util.Arrays; import java.util.Comparator; public class GenericGroup { FuZhuang[] fzList; public void sort(Comparator<? super FuZhuang> c) { Arrays.sort(fzList, c); } public static void main(String[] args) { new GenericGroup().sort(new FZComparator()); } } class FuZhuang { int size; public FuZhuang(int size) { super(); this.size = size; } } class FZComparator implements Comparator<FuZhuang> { @Override public int compare(FuZhuang o1, FuZhuang o2) { return o1.size - o2.size; } }
------解决方案--------------------
不知道你要找的是不是这个
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * * @author XXX * @E-mail monkey_ye@qq.com * @创建时间 2011-7-20 * @param <E> */ public class SortList<E> { /** * 根据对象的相关属性对对象List进行排序 * @param list 需要排序的list * @param method 排序的属性 * @param sort 排序的方式,desc/asc * 例如:sortList.Sort(adt, "getVal", "desc"); */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void Sort(List<E> list, final String method, final String sort){ Collections.sort(list, new Comparator() { public int compare(Object a, Object b) { int ret = 0; try{ Method m1 = ((E)a).getClass().getMethod(method, null); Method m2 = ((E)b).getClass().getMethod(method, null); if(sort != null && "desc".equals(sort))//倒序 ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString()); else//正序 ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString()); }catch(NoSuchMethodException ne){ System.out.println(ne); }catch(IllegalAccessException ie){ System.out.println(ie); }catch(InvocationTargetException it){ System.out.println(it); } return ret; } }); } }
------解决方案--------------------
供参考:
import java.util.*; class Clothing { String brand = null; int price = 0; public Clothing(String brand, int price) { this.brand = brand; this.price = price; } @Override public String toString() { return this.brand+"-"+this.price; } } class GenericGroup { public static void main(String[] args) { GenericGroup gc = new GenericGroup(); gc.sort(new Comparator<Clothing>(){ @Override public int compare(Clothing c1, Clothing c2) { if(c1.price>c2.price) { return 1; } else if(c1.price<c2.price) { return -1; } return 0; } }); } public void sort(Comparator<? super Clothing> c) { Clothing [] clothing = new Clothing[]{new Clothing("361",500),new Clothing("addi",2500),new Clothing("john",1500)}; Arrays.sort(clothing,c); for(Clothing clo: clothing) { System.out.println(clo); } } }