File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Java 5 -Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java 5 -Collection" Watch "Java 5 -Collection" New topic

Java 5 -Collection

Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

I want to know why the following Collection<E> interface methods, accept Collection<?> as the parameter and not Collection<? super E>

boolean containsAll(Collection<?> c)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)

If I create a Collection<String>, does invoking c.containsAll(m) (where m is Collection<Map> make sense? :roll: I dont think so. Could someone explain?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
This must be advanced stuff because this code:

compiles and runs without error. Mind you it doesn't do anything either.

It is rather all confusing
[ December 30, 2004: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33134

Suppose I have a the Dog-Animal-Object hierarchy. Obviously it makes sense to call collectionOfAnimals.containsAll(collectionOfDogs).

However, it also makes sense to call collectionOfDogs.containsAll(collectionOfAnimals). I may not know what is in my collectionOfAnimals. It is entirely possible that it contains only dogs (or is empty) and then the call makes sense.

Another reason is consistency. It must be valid to call collectionOfDogs.containsAll(collectionOfObjects) and collectionOfObjects.containsAll(collectionOfDogs) for the same reasons explained above. collectionOfObjects is equivalent to the pre-java 1.5 Collection. So I can get this functionality by using a Collection without specifying a type because java 1.5 is backward compatible.
[ December 30, 2004: Message edited by: Jeanne Boyarsky ]

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

Thanks Barry and Jeanne. Jeanne, your explanation was quite useful.
I agree. Here's the link:
subject: Java 5 -Collection
It's not a secret anymore!