Java泛型含义<?>

Bla*_*lag 0 java generics

有时候我会看到看起来像的java代码

Class<?>
Run Code Online (Sandbox Code Playgroud)

我不明白它的正确含义.

如果我看到类似的东西:

ComboBox<Order> box = new ComboBox<>();
Run Code Online (Sandbox Code Playgroud)

然后它明确表示该框只能包含类订单中的对象,但是呢<?>?是等于还是完全不同?

Dic*_*ici 6

它被称为通配符,它只是意味着您不需要指定泛型类型.它有时很有用,但一般不应该使用.您可以安全使用它的一种情况是使用类型绑定时:

public void withWildCard(List<? extends Collection<Integer>> collections) { 
    ...
}

public void withoutWildCard(List<Collection<Integer>> collections) { 
    ...
}

List<Collection<Integer>> listOfCollections;
withWildcard(listOfCollections); // valid call
withoutWildcard(listOfCollections); // valid call

List<List<Integer>> listOfLists;
withWildcard(listOfLists); // valid call becase List is a subclass of Collection
withoutWildcard(listOfLists); // invalid call, does not compile because List does not match Collection
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你问题中的片段是错误的.它应该是

ComboBox<Order> box = new ComboBox<>();
Run Code Online (Sandbox Code Playgroud)

如果未在声明端指定泛型类型,则编译器将无法推断菱形运算符(<>)的类型.