-1

所以我有两个版本的相同方法。

版本 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 接口中)?

4

1 回答 1

3

最终引用的类型T必须实现Comparable<T>,而不是您声明绑定类型的类。

让它更简单一点:为了使用您的countGreaterThan方法,数组和elem参数中包含的任何对象都必须是Comparable对象。

这意味着这样的调用是可以接受的:

Integer[] foo = {1, 2, 3, 4, 5};
YourClass.countGreaterThan(foo, 2);

您的类型绑定到Integer, 和Integer implements Comparable<Integer>

这是不可接受的:

Object[] bar = {new Object(), new Object(), new Object()};
YourClass.countGreaterThan(bar, new Object());

您的类型绑定到Object,并且Object没有实现Comparable。相同的逻辑适用于您实现的自定义对象;如果它没有绑定到 Comparable,那么它就不会在适当的范围内。

于 2015-06-02T15:44:35.550 回答