Java - 使用'<>'创建类时意味着什么?

时间:2012-08-22 19:03:22

标签: java class

我刚刚创建了一个这样的类:NameOfTheClass<Raeaeraear>。这是什么意思?为什么我可以随意添加任何我想要的东西?

2 个答案:

答案 0 :(得分:1)

这就是所谓的泛型。泛型用于“告诉”类的实例它将使用哪种类型,使用f.ex a List

List<People> myPeopleList = new ArrayList<People>(); 

此处列表已参数化。如果你看一下List-interface源代码,它就像这样声明,这意味着接口List是通用的。

public interface List<E> extends Collection<E> {
...

在你的情况下,NameOfTheClass类的实现方式与此类似,注意:泛型可以应用于类或接口。

public class NameOfTheClass<E> {
....
public doSome(E e){
    doSomeGenericOperationWith(e);
}

这个类可以像这样使用:

NameOfTheClass<AType> instance = new NameOfTheClass<AType>();
Atype yourType = ...
doSome(yourType);

注意:任何使用doSome()方法都需要Atype类型的参数,这将由Java编译器处理。因此,如果您尝试使用其他类型调用该方法,则编译错误将会增加。

更多读数:http://docs.oracle.com/javase/tutorial/java/generics/why.html

答案 1 :(得分:0)

当您使用<>时,编译器会关闭检查泛型类型。当编译器需要知道类型时,您无法使用<>

e.g。

// compiles ok because the compiler knows not to check the type.
List<Integer> ints = new ArrayList<>(); 

// compiler needs to know the type, so this doesn't compile.
List<Integer> ints = new ArrayList<>() {};