Comparing the values of two generic Numbers

后端 未结 12 1797
小鲜肉
小鲜肉 2020-11-27 04:48

I want to compare to variables, both of type T extends Number. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 05:22

    This should work for all classes that extend Number, and are Comparable to themselves.

    class NumberComparator implements Comparator {
    
        public int compare(T a, T b){
            if (a instanceof Comparable) 
                if (a.getClass().equals(b.getClass()))
                    return ((Comparable)a).compareTo(b);        
            throw new UnsupportedOperationException();
        }
    }
    

提交回复
热议问题