Comparing the values of two generic Numbers

后端 未结 12 1758
小鲜肉
小鲜肉 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:15

    One solution that might work for you is to work not with T extends Number but with T extends Number & Comparable. This type means: "T can only be set to types that implements both the interfaces."

    That allows you to write code that works with all comparable numbers. Statically typed and elegant.

    This is the same solution that BennyBoy proposes, but it works with all kinds of methods, not only with comparator classes.

    public static > void compfunc(T n1, T n2) {
        if (n1.compareTo(n2) > 0) System.out.println("n1 is bigger");
    }
    
    public void test() {
        compfunc(2, 1); // Works with Integer.
        compfunc(2.0, 1.0); // And all other types that are subtypes of both Number and Comparable.
        compfunc(2, 1.0); // Compilation error! Different types.
        compfunc(new AtomicInteger(1), new AtomicInteger(2)); // Compilation error! Not subtype of Comparable
    }
    

提交回复
热议问题