简体   繁体   中英

Java List interface method: containsAll(Collection<?> c)

I understand how you would write a contains(E item) method, by checking each item in this and returning true if you find that one of the elements of this is equal to item.

But how would you deal with the Wildcard type for the collection when you go through c? Are you supposed to for example say:

for (Object item: c) {

How would you reference that it is a ? type.

The compiler didn't like:

for (? item: c) 

or

for (<?> item: c)

Yes you do write

for (Object item: c) {

There simply is no type called ? -- it's a wildcard that means anything is allowable here (ie there are no bounds to the allowed type); it is not a "wildcard type" . The best you can do is use Object as you know nothing about the elements in such a collection. The point of wildcards is to say the type is unknown .

The wildcard is quite different from

Collection<E>

or

Collection<Object>

There are some SO questions that address these differences; one is Java Generics (Wildcards) .

But again, the key idea is that ? is not a type, it is more of a meta-level concept. That is why you cannot declare variables of that "type."

是的,使用for(Object item: c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM