Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection:containsAll

 
kirba devi
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
import java.util.*;

class TestCollection {

public static void main(String[] args) {
System.out.println("************TestCollection**********");
List<String> liss1=new ArrayList<String>();
liss1.add("wer");
liss1.add("wera");
liss1.add("er");

List<String> liss=new ArrayList<String>();//Line1
liss.add("wer");
liss.add("w");
liss.add("er");
List<Number> lisint=new ArrayList<Number>();//Line2
lisint.add(1);
lisint.add(1.67);
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!!!

Regards
Kirba
 
kirba devi
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Output:
************TestCollection**********
false
 
Justin Smith
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!

Regards
Kirba
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic