On Generics
Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.
When we declare c to be of type Collection
JDK 1.5
You might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit “template metaprogramming.”
Is the following code snippet legal?
List<String> ls = new ArrayList<String>(); //1 List<Object> lo = ls; //2
Line 1 is definitely legal. But line 2 will give a compile time error.
Well, take a look at the next few lines:
lo.add(new Object()); // 3 String s = ls.get(0); // 4: attempts to assign an Object to a String!
In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some
generic type declaration, it is not the case that G
It’s written as
Collection<?>(pronounced “collection of unknown”) , that is, a collection whose element type matches anything.
Collection> c = new ArrayListLine 2 will give a compile time error since we don't know what element type of c stands for, we cannot add arbitrary data to it.(); //1 c.add(new Object()); //2
Posted at 12:40AM Mar 09, 2008 by Manveen Kaur in General | Comments[0]