Type checking in a method with generic parameters

publicclass Utils{

publicstatic <T>void CopyToGeneric(Collection f, Collection<T> t)throws ClassCastException{

if(f !=null && t !=null)for (Object o : f) t.add((T)o);

}

}

...

list =new ArrayList();

list.add(new Integer(1));

list.add("qqq");

listOfStrings =new ArrayList<String>();

Utils.CopyToGeneric(list, listOfStrings);// This is where I think I should be getting a ClassCastException when the Integer is cast to a String

try{

for (String s : listOfStrings){// This is where the only exception is thrown

System.out.printf("\t'%s'\n", s);

}

}catch (ClassCastException e){

e.printStackTrace();

}

I understand why I get the second exception. But I don't understand why the the cast does not throw an exception.

[1778 byte] By [jGarya] at [2007-11-27 8:47:51]
# 1
Because there is no runtime check of generics. More exactly, generics are a compile-time feature, where erasure will be applied to generic types.see http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#What%20is%20type%20erasure?
stefan.schulza at 2007-7-12 20:53:44 > top of Java-index,Core,Core APIs...