[英]generic: extends Number & Comparable Basic understanding
class MyTest<K,V extends Number & Comparable> implements Comparable<MyTest>{
private K key;
private V value;
}
What does this mean K, V extends Number & Comparable
? 这意味着K, V extends Number & Comparable
吗? In above statement MyTest
is implementing a comparable interface, But I am not able to figure out K,V
and why there is Number & Comparable. 在上面的声明中, MyTest
正在实现一个可比较的接口,但是我无法弄清楚K,V
以及为什么存在Number&Comparable。 k,v are not an interface. k,v不是接口。 Can some one enlighten me on this. 有人可以启发我。
This class accepts two generic arguments, first of them is named as K
(which is likely to be used as "key"), and the second of them is named as V
(which is likely to be used as "value"). 此类接受两个通用参数,第一个称为K
(很可能用作“键”),第二个称为V
(很可能用作“值”)。
V extends Number & Comparable
part means that the class accepts only those V
values which both extend Number
abstract class and implement Comparable
interface. V extends Number & Comparable
部分意味着该类仅接受既扩展Number
抽象类又实现Comparable
接口的V
值。 Examples of such classes are standard JDK Integer
, Float
, Long
, Double
or BigInteger
. 此类的示例为标准JDK Integer
, Float
, Long
, Double
或BigInteger
。 If you want to use your own class as V
, you should extend Number
and implement Comparable
at the same time. 如果要将自己的类用作V
,则应扩展Number
并同时实现Comparable
。 No restriction for the K
is applied: you may use any class for K
. 没有对K
限制:您可以对K
使用任何类。 For example, this type is valid: 例如,此类型有效:
MyTest<String, Integer> myTest; // K = String, V = Integer
But this one will result in compilation error: 但这会导致编译错误:
MyTest<Integer, String> myTest; // K = Integer, V = String, does not implement Number
We can subtype a generic class or interface by extending or implementing it. 我们可以通过扩展或实现来泛型一个通用类或接口。 The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses. 一个类或接口的类型参数与另一类或接口的类型参数之间的关系由extend和Implements子句确定。
For example, ArrayList implements List that extends Collection, so ArrayList is a subtype of List and List is subtype of Collection. 例如,ArrayList实现扩展了Collection的List,因此ArrayList是List的子类型,而List是Collection的子类型。 Here K represents key and V represents value. 这里K代表键,V代表值。 then from your code the Java compiler replaces the type parameter K with the Number and V with the Comparable, as below code: 然后从您的代码中,Java编译器将类型参数K替换为Number,将V替换为Comparable,如下代码:
private Number key;
private Comparable value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.