[英]Java generic class syntax
I know that I can create a class in java like this: 我知道我可以在java中创建一个类,如下所示:
public class test {/*some code*/}
But now I have this: 但现在我有这个:
public class coada < T extends Number & Comparable < Number>> {
List <T> pq = new ArrayList <T>();
public void add(T e , List <T> c) {
c.add(e);
Collections.sort(c);
}
public void remove(List < ? extends Number> c) {
c.remove(0);
}
}
I don't understand the more complicated syntax of the angled brackets and parameter lists. 我不明白斜角括号和参数列表的更复杂的语法。
I have these questions: 我有这些问题:
Can someone clarify the syntax used in the example? 有人可以澄清示例中使用的语法吗?
I know Java doesn't support multiple inheritance. 我知道Java不支持多重继承。 So how are Number & Comparable possible? 那么Number&Comparable怎么可能呢?
I thought generics are used for collections, not classes, so, how can class coada
have a type parameter? 我认为泛型用于集合,而不是类,所以, class coada
如何具有类型参数?
T extends Number & Comparable <Number>
T extends Number and implements Comparable T extends Number & Comparable <Number>
T extends Number并实现Comparable
Generics don't require type to be a collection. 泛型不要求类型是集合。
Comparable
is an interface, so T
can extend Number
and implement Comparable<Number>
(and any number of other interfaces) at the same time. Comparable
是一个接口,因此T
可以扩展Number
并同时实现Comparable<Number>
(以及任意数量的其他接口)。
As for your second question, any class can have type parameters, not only Collection
s. 至于你的第二个问题,任何类都可以有类型参数,而不仅仅是Collection
s。 coada < T extends Number & Comparable < Number>>
means that the class coada
has a type parameter called T which must be either Number
or a sub-class of Number
and implement the interface Comparable<Number>
. coada < T extends Number & Comparable < Number>>
意味着该类coada
具有类型参数称为T这必须是Number
或子类的Number
和实现接口Comparable<Number>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.