今天早上我遇到了这段代码,我完全不知道这意味着什么.谁能解释我这些<T>代表什么?例如:
public class MyClass<T>
...
some bits of code then
private Something<T> so;
private OtherThing<T> to;
private Class<T> c;
Run Code Online (Sandbox Code Playgroud)
谢谢
Lar*_*ren 13
你已经碰到了"泛型".本指南中对它们进行了很好的解释.
简而言之,它们允许您指定存储类的类型,例如a List或Setcontains.如果你写Set<String>,你已经声明这个集合必须只包含Strings,并且如果你试图在其中放入其他内容将会出现编译错误:
Set<String> stringSet = new HashSet<String>();
stringSet.add("hello"); //ok.
stringSet.add(3);
^^^^^^^^^^^ //does not compile
Run Code Online (Sandbox Code Playgroud)
此外,泛型可以做的另一个有用的例子是它们允许您更密切地指定一个抽象类:
public abstract class AbstClass<T extends Variable> {
Run Code Online (Sandbox Code Playgroud)
通过这种方式,扩展类不必扩展Variable,但是它们需要扩展扩展的类Variable.
因此,处理a的方法AbstClass可以这样定义:
public void doThing(AbstClass<?> abstExtension) {
Run Code Online (Sandbox Code Playgroud)
其中?是一个通配符,表示"所有AbstClass与某些类一起扩展的类Variable".
| 归档时间: |
|
| 查看次数: |
379 次 |
| 最近记录: |