简体   繁体   English

如何将原语与Java泛型进行比较?

[英]How to compare primitives with Java Generics?

I am learning java Generics. 我正在学习Java泛型。 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) . 要比较两个Comparable对象, 必须使用compareTo ,这里是x.compareTo(y) Your method can be written 您的方法可以写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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