Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java 5 -Collection

 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Thanks
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34422
347
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pradeep,
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 ]
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Barry and Jeanne. Jeanne, your explanation was quite useful.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic