[英]Java bounded type parameters
1.I thought that Interfaces in Java don't have implementations, so how can I use my compareTo() here? 1.我以为Java中的Interfaces没有实现,所以如何在这里使用我的compareTo()?
2.As far as I knew the extends keyword can add new methods to an interface in order to be implemented later. 2.据我所知, extends关键字可以向接口添加新方法,以便以后实现。 So I don't understand what/how am I exactly extending right here ?
所以我不明白我在这里到底是什么/如何扩展?
Thanks 谢谢
public class Compare {
// simple comparison operator < > ... works only on primitives
// that's why we need the Comparable
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;
}
}
Interfaces in Java don't have implementations, but you can't create an instance of an interface. Java中的接口没有实现,但是您不能创建接口的实例。 (Try it - what happens when you include
new List()
in your code?) You can only create an instance of a class implementing that interface, and the class is required to implement the interface's methods. (尝试一下-在代码中包含
new List()
时会发生什么?)您只能创建实现该接口的类的实例,并且该类是实现接口的方法所必需的。
In this case, you're not extending anything at all yourself. 在这种情况下,您根本不会扩展任何内容。 You just indicate 'this method can only be used for classes
T
which extend/implement the Comparable<T>
interface'. 您仅表示“此方法只能用于扩展/实现
Comparable<T>
接口的类T
”。
Actually from Java 8 onwards, Interfaces can have (default, partial) implementation, but that's an aside. 实际上,从Java 8开始,接口可以具有(默认,部分)实现,但这是一个问题。 The confusing thing here is that the keyword
extends
has two usages: 令人困惑的是,关键字
extends
有两种用法:
List<T extends Comparable>
. List<T extends Comparable>
。 Using the same key word was a decision made when they introduced this, presumably to emphasise how the kind of class that is suitable for this Generic T
would itself have to extend Comparable
(for example). T
的类本身必须如何扩展 Comparable
(例如)。 As classes and interfaces in Java share the same hierarchies, it doesn't really matter which you use here (though interfaces are advisable).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.