Java 带接口的泛型方法的边界类型参数?
所以我有两个相同方法的版本 第1版:Java 带接口的泛型方法的边界类型参数?,java,generics,methods,interface,generic-method,Java,Generics,Methods,Interface,Generic Method,所以我有两个相同方法的版本 第1版: public static <T> int countGreaterThan(T[] anArray, T elem) { int count = 0; for (T e : anArray) { if (e > elem) count++; } return count; } pub
public static <T> int countGreaterThan(T[] anArray, T elem)
{
int count = 0;
for (T e : anArray)
{
if (e > elem)
count++;
}
return count;
}
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem)
{
int count = 0;
for (T e : anArray)
{
if (e.compareTo(elem) > 0)
count++;
}
return count;
}
为了在不同的类中实现该接口,我需要在这些类中为舞蹈接口中的方法编写方法体
public class theMoonwalk implements Dance {
public void boogie(int count) {
System.out.println("Slide " + count + " times!");
}
public void mJ() {
System.out.println("Michael Jackson did this dance!");
}
public class theHustle implements Dance {
public void boogie(int steps) {
System.out.println("Step " + steps + " times!");
}
}
public class theJitterBug implements Dance {
public void boogie(int twists) {
System.out.println("Twist " + twists + " times!");
}
}
为什么我不为compareTo()编写一个方法体(因为compareTo()的可比接口中不包含方法体)?最终引用的类型必须实现
Comparable
,而不是声明绑定类型的类
更简单一点:为了使用countGreaterThan
方法,数组和elem
参数中包含的任何对象都必须是可比的对象
这意味着这样的调用是可以接受的:
Integer[] foo = {1, 2, 3, 4, 5};
YourClass.countGreaterThan(foo, 2);
Object[] bar = {new Object(), new Object(), new Object()};
YourClass.countGreaterThan(bar, new Object());
您的类型被绑定到Integer
,而Integer实现了Comparable
这是不可接受的:
Integer[] foo = {1, 2, 3, 4, 5};
YourClass.countGreaterThan(foo, 2);
Object[] bar = {new Object(), new Object(), new Object()};
YourClass.countGreaterThan(bar, new Object());
您的类型已绑定到对象
,并且对象
未实现可比
。相同的逻辑适用于您实现的自定义对象;如果它没有绑定到Comparable,那么它就不会处于正确的绑定中。你是在问为什么不必将public int compareTo(to)
方法编写出来?我不明白。包含countGreaterThan
方法的类不必实现compariable
。。。你能澄清一下你在问什么吗?@Patrick泛型类型T必须实现compareTo
方法,而不是包含泛型方法的类。这不是重复的。
Object[] bar = {new Object(), new Object(), new Object()};
YourClass.countGreaterThan(bar, new Object());