[英]Modifying a method so the arguments can be any type that implements Comparable
I would like to modify the following method so its arguments can be of any type that implements the Comparable
interface. 我想修改以下方法,以便它的参数可以是实现
Comparable
接口的任何类型。 The method's return type should be the same as the type of its parameter variables. 方法的返回类型应与其参数变量的类型相同。
public static int max(int a, int b) {
if (a >b)
return a;
else
return b;
}
So in modifying it, I could just use <T extends Comparable<T>>
, but how would I go about making the return types the same? 所以在修改它时,我可以使用
<T extends Comparable<T>>
,但是我如何才能使返回类型相同呢?
You essentially want something like this: 你基本上想要这样的东西:
public static <T extends Comparable<T>> T max(T a, T b) {
int n = a.compareTo(b);
if (n > 0)
return a;
if (n < 0)
return b;
return a;
}
You can of course simplify this to the following (thank you to @pickypg for the notice): 您当然可以将此简化为以下内容(感谢@pickypg的通知):
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) < 1 ? b : a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.