排序一个list数组中的元素

    技术2022-05-20  36

    public class SortList<E> { @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; } }); } }

     

    1:动态的获得方法   如:getUserId

    2:动态的调用方法  如:method1.invoke((E)a,null)

     

    sort里面的compareto方法,里面如果返回时-1  就不把object a ,b 调换 ,如果要倒叙排序好办法就是把 返回的值编程整的 ,可以把内部比较的时候用 b  - a ,这样返回正数, 就巧妙的实现了倒叙了 ,It is amazing

    边学便用 今天学了得到Method的方法 以后就可以这样用了 Method m11=(a).getClass(I).getMethod(method,null

    );

     

     

    Collections.sort(list, new Comparator() {             int ret = 0;             public int compare(Object o1, Object o2) {

    }

    中如果compare 方法返回时-1 ,则不会调换o1 o2顺序,如果放回为1,则会调换o1 o2顺序


    最新回复(0)