How to use Comparator in Java to sort

后端 未结 14 1824
时光取名叫无心
时光取名叫无心 2020-11-22 02:19

I learned how to use the comparable but I\'m having difficulty with the Comparator. I am having a error in my code:

Exception in thread \"main\" java.lang.C         


        
14条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 02:59

    Here's an example of a Comparator that will work for any zero arg method that returns a Comparable. Does something like this exist in a jdk or library?

    import java.lang.reflect.Method;
    import java.util.Comparator;
    
    public class NamedMethodComparator implements Comparator {
    
        //
        // instance variables
        //
    
        private String methodName;
    
        private boolean isAsc;
    
        //
        // constructor
        //
    
        public NamedMethodComparator(String methodName, boolean isAsc) {
            this.methodName = methodName;
            this.isAsc = isAsc;
        }
    
        /**
         * Method to compare two objects using the method named in the constructor.
         */
        @Override
        public int compare(Object obj1, Object obj2) {
            Comparable comp1 = getValue(obj1, methodName);
            Comparable comp2 = getValue(obj2, methodName);
            if (isAsc) {
                return comp1.compareTo(comp2);
            } else {
                return comp2.compareTo(comp1);
            }
        }
    
        //
        // implementation
        //
    
        private Comparable getValue(Object obj, String methodName) {
            Method method = getMethod(obj, methodName);
            Comparable comp = getValue(obj, method);
            return comp;
        }
    
        private Method getMethod(Object obj, String methodName) {
            try {
                Class[] signature = {};
                Method method = obj.getClass().getMethod(methodName, signature);
                return method;
            } catch (Exception exp) {
                throw new RuntimeException(exp);
            }
        }
    
        private Comparable getValue(Object obj, Method method) {
            Object[] args = {};
            try {
                Object rtn = method.invoke(obj, args);
                Comparable comp = (Comparable) rtn;
                return comp;
            } catch (Exception exp) {
                throw new RuntimeException(exp);
            }
        }
    
    }
    
        

    提交回复
    热议问题