问题
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);
}
}
What does <? extends T>
do? How does it differ from <T>
?
EDIT:
Followup question: Does BookCase extends ArrayList<Book>
mean that BookCase
extends Book
?
回答1:
Consider the following
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
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.
回答2:
Both Collection<Book>
and Collection<? extends Book>
represents a collection that can hold Book
instances and objects that can be considered to be a Book
through the is-a relationship. This property extends to interfaces as well.
The difference here is that the latter form is considered to be bounded. Depending on the bound, you would not be able to add or remove elements from this collection.
? extends T
is a upper bounded wildcard. In effect, it describes a hierarchical bound between some type (?
) at the low end, and Book
at the high end. It is inclusive, so you can store instances of Book
in there, but if you had other classes and interfaces, such as:
class Novella extends Book {}
class Magazine extends Book {}
class ComicBook extends Book{}
class Manga extends Magazine {}
class Dictionary extends Book {}
class ForeignLanguageDictionary<T extends Language> extends Dictionary {}
interface Language {}
...you could find any of those instances inside of a Collection<? extends Book>
.
Recall that I mentioned that you may not be able to add or remove things from this collection? Remember this convention:
Producer extends; consumer super.
Note that this is from the perspective of the collection; if the collection is bounded with extends
, it's a producer; if it's bounded with super
, it's a consumer.
That said, from this collection's perspective, it has already produced all of its records, so you cannot add new ones to it.
List<? extends Book> books = new ArrayList<>(); // permanently empty
books.add(new Book()); // illegal
If it were the case that you had it bound with ? super Book
, you could not retrieve elements from it in a sane way - you'd have to retrieve them as Object
instead, which isn't concise.
List<? super Book> books = new ArrayList<>();
books.add(new Book());
books.add(new Manga());
Book book = books.get(0); // can't guarantee what Book I get back
Chiefly, if you are bound with ? super T
, you only ever intend to insert elements into that collection.
Followup question: Does
BookCase extends ArrayList<Book>
mean thatBookCase extends Book
?
No. A BookCase
in that instance is an ArrayList
, not a Book
. It so happens to be the case that the array list is bound to store books, but it itself is not a Book
.
回答3:
Check out this from the documentation.
In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G is a subtype of G. This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions.
Take a look at the next page about wildcards too.
So basically when you write void doStuff(List<Book>){}
you can only do stuff to a list of Book
objects ONLY.
Not Novel
s, not Magazine
s, not ComicBook
s.
Again, this is because although Novel
extends Book
, G<Novel>
does not actually extend G<Book>
. It is not very intuitive, but the example in the documentation will help you see it.
回答4:
Here's the example that clearly shows the difference between Collection<? extends Book>
and Collection<Book>
:
public class Test {
public static void main(String[] args) {
BookCase bookCase1 = new BookCase();
BookCase bookCase2 = new BookCase(bookCase1);
List<FictionBook> fictionBooks = new ArrayList<>();
BookCase bookCase3 = new BookCase(fictionBooks);
}
}
class Book {}
class FictionBook extends Book {}
class BookCase extends ArrayList<Book> {
public BookCase() {
}
//does not act same as public BookCase(Collection<Book> c) {
public BookCase(Collection<? extends Book> c) {
super(c);
}
}
that code compiles. If you change the BookCase
s constructor parameter to Collection<Book>
, this example won't compile.
回答5:
List<Book>
is a list that may contain any book. Because there is no restriction on the kind of book, you can add any book to it.
List<? extends Book>
is as well a list that contains books, but there might but further restrictions. Maybe in fact it is a List<PoetryBook>
and it may only store instances of PoetryBook
, you can only be sure that every item inside this list is a book. Because of this possible restriction you can't add any items to this list.
Consider a method that takes a list of books and returns the book with the most pages.
Book getBookWithMostPages(List<? extends Book>) {
...
}
This method can be called with List<Book>
or with List<PoetryBook>
.
If you change the signature to
Book getBookWithMostPages(Iterable<? extends Book>) {
...
}
then it can also be used with Set<ScienceBook>
or anything that is iterable and contains books.
来源:https://stackoverflow.com/questions/28464614/collection-extends-t-vs-collectiont