集合< ;?扩展T> vs Collection T
尝试理解 Spring的概念后MVC ,我遇到了以前从未见过的表达式Collection<? extends Book>
.我试图自己弄清楚它,但是我发现使用Collection<? extends Book>
和Collection<Book>
之间没有区别.我猜想它只允许Book的扩展,但是它也允许Book的扩展.所以抓.我曾尝试使用Google,但自那以后呢?是Google中的通配符,它几乎无法搜索.我已经在stackoverflow上搜索了答案,但是有关此问题的所有问题(例如 List< ;?扩展了MyType> 和< ;?扩展> Java语法)已经假定具备Collection<? extends T>
的知识.这是最初引起我兴趣的代码:
After trying to understand the concepts at Spring MVC, I came across the expression Collection<? extends Book>
which I have never seen before. I have tried to figure it out on my own, but I am seeing no difference between using Collection<? extends Book>
and Collection<Book>
. I was guessing that it only allowed for extensions of Book, but it does allow for Book as well. So scratch that. I have tried using Google, but since ? is a wildcard in google, it makes it nearly impossible to search for. I have searched stackoverflow for the answer, but all questions about this (such as List<? extends MyType> and <? extends > Java syntax) already assume knowledge of Collection<? extends T>
. Here is the code that has initially intrigued my interest:
import java.util.ArrayList;
import java.util.Collection;
public class Book {
public static void main(String[] args) {
BookCase bookCase1 = new BookCase();
BookCase bookCase2 = new BookCase(bookCase1);
}
}
class BookCase extends ArrayList<Book> {
public BookCase() {
}
//acts same as public BookCase(Collection<Book> c) {
public BookCase(Collection<? extends Book> c) {
super(c);
}
}
<? extends T>
的作用是什么?它与<T>
有什么区别?
What does <? extends T>
do? How does it differ from <T>
?
后续问题:BookCase extends ArrayList<Book>
表示BookCase
扩展了Book
吗?
Followup question: Does BookCase extends ArrayList<Book>
mean that BookCase
extends Book
?
请考虑以下内容
class Animal { }
class Horse extends Animal { }
private static void specific(List<Animal> param) { }
private static void wildcard(List<? extends Animal> param) { }
没有扩展语法,您只能在签名中使用确切的类
Without the extends syntax you can only use the exact class in the signature
specific(new ArrayList<Horse>()); // <== compiler error
通过通配符扩展,您可以允许Animal的任何子类
With the wildcard extends you can allow any subclasses of Animal
wildcard(new ArrayList<Horse>()); // <== OK
通常最好使用?扩展语法,因为它使您的代码更具可重用性和面向未来.
It's generally better to use the ? extends syntax as it makes your code more reusable and future-proof.