所以我有两个版本的相同方法。
版本 1:
public static <T> int countGreaterThan(T[] anArray, T elem)
{
int count = 0;
for (T e : anArray)
{
if (e > elem)
count++;
}
return count;
}
版本 2:
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;
}
Eclipse 抱怨版本 1,因为 > 运算符只能在比较原语时使用,这对我来说很有意义。
所以为了解决这个问题,互联网告诉我使用由 Comparable 接口限制的类型参数。这就是我开始失去对正在发生的事情的掌握的地方......
从我对接口的基本理解来看,实现接口的类必须为接口中声明的每个方法提供一个方法体。
因此,为什么版本 2不必看起来像这样?
public int compareTo(T o)
{
//stuff for method body
}
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;
}
^我知道这不是正确的语法,但我这样做只是为了说明我的问题,即为什么在这种情况下我不必为 Comparable 接口中的方法编写方法体。
请尽量保持通俗易懂的解释。我一直在自学这些东西,所以当我进一步研究主题时,简单的解释可以帮助我理解主题的更多技术方面。
很抱歉造成混乱,让我澄清一下。
这是 Comparable 接口的代码:
public interface Comparable<T> {
public int compareTo(T o);
}
compareTo() 没有方法体,因为它是一个接口。为什么我不必手动为 compareTO() 编写一个主体,这样我就可以在我的 countGreaterThan() 方法中使用该接口?
是否因为该接口是 Java Collections Framework 的一部分(如果这就是原因,请解释它是如何工作的)
这是我创建自己的界面的另一种情况:
public interface Dance { //an interface
public void boogie(int 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 接口中)?