简体   繁体   中英

How to compare primitives with Java Generics?

I am learning java Generics. I would like to compare primitives using unbounded Generics.I have the following code,

public static <T extends Comparable<T>> T max(T x, T y) {
    return x > y ? x : y;
}

but it won't compile. The error is:

The operator > is undefined for the argument type(s) T

To compare two Comparable objects, you must use compareTo , here x.compareTo(y) . Your method can be written

return x.compareTo(y) > 0 ? x : y;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM