On Generics

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, this tells us something about the variable c that holds true wherever and whenever it is used, and the compiler guarantees it (assuming the program compiles without warnings). A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks whether the programmer is right only at run time.

When was Java Generics introduced?

JDK 1.5

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 is a subtype of G. This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions.

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 ArrayList(); //1
c.add(new Object()); //2
Line 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.
Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

manveen

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today