[英]How do I write generic Java method and compare two variables of the generic type inside the method?
I have written the following code: 我写了以下代码:
private static <T> T getMax(T[] array) {
if(array.length == 0) {
return null;
}
T max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max)
max = array[i];
}
return max;
}
The problem is in this line: if(array[i] > max)
. 问题出在这一行: if(array[i] > max)
。
I understand that Java can't understand the >
operator in case of unknown/arbitrary classes. 我知道Java在未知/任意类的情况下无法理解>
运算符。
At the same time, I don't want to write different methods for the objects of the classes that I know I'll be sending. 同时,我不想为我知道将要发送的类的对象编写不同的方法。
Is there a workaround? 有解决方法吗?
You need to change T
to T extends Comparable<T>
and use the compareTo
method. 您需要将T
更改为T extends Comparable<T>
并使用compareTo
方法。 That is: 那是:
private static <T extends Comparable<T>> T getMax(T[] array)
, and private static <T extends Comparable<T>> T getMax(T[] array)
,and if (array[i].compareTo(max) > 0) { ... }
But note that you can use 但请注意,您可以使用
maxElement = Collections.max(Arrays.asList(array));
Yes, there is a workaround, by adding a Comparable
upper bound to T
. 是的,通过向T
添加Comparable
上限,有一种解决方法。
Because the <
operator doesn't work on objects, you must use the equivalent functionality, which is the compareTo
method in the Comparable
interface. 因为<
运算符不能处理对象,所以必须使用等效功能,即Comparable
接口中的compareTo
方法。
Ensure that the type T
is Comparable
by providing an upper bound. 通过提供上限确保类型T
是Comparable
的。
private static <T extends Comparable<T>> T getMax(T[] array)
Then, in place of the >
operator, call compareTo
: 然后,代替>
运算符,调用compareTo
:
if(array[i].compareTo(max) > 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.