It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collection:containsAll Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collection:containsAll" Watch "Collection:containsAll" New topic


kirba devi
Ranch Hand

Joined: Jun 29, 2007
Posts: 50
import java.util.*;

class TestCollection {

public static void main(String[] args) {
List<String> liss1=new ArrayList<String>();

List<String> liss=new ArrayList<String>();//Line1
List<Number> lisint=new ArrayList<Number>();//Line2
System.out.println(liss.containsAll(lisint));//Line 3

generic type in Line1 List<String>-->list of Strings
generic type in Line2 List<Integer>-->list of Integers
At Line3 why it is not thrrowing ClassCastException ?
Please correct if i am wrong!!!

kirba devi
Ranch Hand

Joined: Jun 29, 2007
Posts: 50
Justin Smith

Joined: Jul 24, 2008
Posts: 19
Hi kirba,

The line3 which is <Collection>containsAll(<Collection> is checking whether the given object has all the elements in another collection. If all the elements were present it is going to return true and if not it is going to return false. If you don't pass Collection in any of the comparison then you would get an compilation error.

Hope this clarifies your doubt..
Paul Beckett
Ranch Hand

Joined: Jun 14, 2008
Posts: 96
I always find the best way to answer this sort of question is to look at the javadoc.

If you look at the Collection interface, the containsAll method has signature:

therefore you can check against any type of collection that contains Objects. It could (but doesn't) limit the collection to the E type parameter.
It also says that the ClassCastException is optional so therefore dependent upon the implementation.

Incidentally, the containsAll method in ArrayList is inherited from the AbstractCollection so you may want to look there for more info.

One way you could think about the implementation is like so (you will be able to find the actual source somewhere):

[ July 25, 2008: Message edited by: Paul Beckett ]
kirba devi
Ranch Hand

Joined: Jun 29, 2007
Posts: 50
Hi Paul
Read the api for containsAll() method,so you are saying list of elements in one collection can be compared with list of elements of another collection with/without using generics.

What is the exact use of wildcard capture?
Please reply as i am prpearing for scjp!!!

I agree. Here's the link:
subject: Collection:containsAll
jQuery in Action, 3rd edition