-1

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

4

2 回答 2

1

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

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

这里列表是参数化的。如果你看一下 List 接口源代码,它是这样声明的,这意味着接口 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

于 2012-08-22T19:17:29.080 回答
0

当您使用 a 时<>,编译器会关闭检查泛型类型。当编译器需要知道你不能使用的类型时<>

例如

// 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<>() {}; 
于 2012-08-22T19:14:07.707 回答