[英]How to use generics to specify super-class relationships with Comparable type
I created a method getMax that takes and array of Comparable as a parameter and compares the elements to find the max element, but I also have to implement generics to specify super-class relationships and I do not really understand how I would do that. 我创建了一个getMax方法,该方法将Comparable数组作为参数,并比较元素以找到max元素,但是我还必须实现泛型来指定超类关系,但我不太了解如何做到这一点。 Below is the src for my non-generic method 以下是我的非泛型方法的src
public static Comparable getMax(Comparable [] array){
Comparable max=array[0];
for(int x=0; x<array.length;x++){
if(array[x].compareTo(max)==1)
max=array[x];
}
return max;
}
You can rewrite your getMax
method with generics like this: 您可以使用如下泛型重写getMax
方法:
public static <T extends Comparable<T>> T getMax(T[] array){
T max=array[0];
for(int x=0; x<array.length;x++){
if(array[x].compareTo(max)==1)
max=array[x];
}
return max;
}
(You see, the trick is replacing Comparable
by T
, and declaring T
to be Comparable<T>
.) (您会发现,诀窍是用T
代替Comparable
,并声明T
为Comparable<T>
。)
Then, for example you can use it like this: 然后,例如,您可以像这样使用它:
String[] strings = { "Bob", "Alice", "Charlie" };
String maxString = getMax(strings); // gives "Charlie"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.