Wednesday, February 6, 2008

Part 2 of 4: Generics in Java


Lets see how GENERICS work with Legacy Code. By Legacy code we mean - code which has been written with Java Version 1.4 and before.


In this era of digital world, everything has been digitalized so is the PASSPORT. Now a days information is stored in bar-code fashion on passport.Based on this suppose we have one List.
List< digital_Passport > passportList = new ArrayList< digital_Passport >( );

Suppose we have a Legacy Method -

public void legacy_Add_Method( List passportData ){
passportData.add( new Old_Passport() );

Lets say we made a call to Legacy Method-

legacy_Add_Method( passportList );

This actually means -
List passportData = new ArrayList< digital_Passport>( )

Think from another point of view, Just because you have a new passport and airport system can recognize your passport, airport authority can not reject people with old passport. Similar way, although this sound odd but JAVA has to allow an old Legacy method be called with new Generic Type Collection Object, but being good JAVA tells this unusual assignment by issuing a COMPILER WARNING.

Another point to remember is - COMPILATION and ERROR are different thing and COMPILATION WITH WARNING is a SUCCESSFUL COMPILATION.

Practice Question :
import java.util.*;
class Test {
public static void main(String [] args) {
Set vals = new TreeSet< String >();

What is true about the above question:
a)Does not Compile
b)Compiles with warning and prints output [one, 1, two]
c)Compiles without warning and prints output [one, 1, two]
d)Compiles with warning and throws exception at runtime
e)Compiles without warning and throws exception at runtime

Answer :
we know that it will compile with warning, so this removes option A and C. Another point about Set
is - Its ordered and sorted collection and String/Integer can not be sorted together. So answer is D.

No comments: