By manveen on Mar 08, 2008
What is 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
When was Java Generics introduced?
How is this different from C++'s template mechanism?
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.”
Generics and subtyping
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
What is the supertype of all kinds of collections?
It’s written as
Collection<?>(pronounced “collection of unknown”) , that is, a collection whose element type matches anything.
Is this valid?Is the following code valid?
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