Generic Programming in JAVA- An overview

Generics

–          Ensures Type safety.

–          Type check performed by compiler at compile-time.

–          No type casting required in most cases.

–          Minimize run-time error ClassCastException highly.

–          Ensures backward compatibility by means of Type Erasure.

Erasure

Erasure is the process occurs at compile time, which converts the Generic code to legacy code.  Type Erasure erases all type parameter information and inserts appropriate casts in the code.

Key Points:

Type parameters must be class types.  Using primitive types will cause compiler error.

Declaring and initializing a generic collection:

Prior to Java 5, a collection can take any kind of objects and when you retrieve, you will get only objects of type ‘Object’ always.

With reference to below code, list must be both declared and initialized with the generic type. The below code compiles successfully. Here list can accept any arbitrary object.

List list = new ArrayList<Integer>();

list.add(5);

list.add(4);

list.add(“10”);

for(Iterator<Integer> it = list.iterator(); it.hasNext(); ) {

int value = it.next()*10;

System.out.println(value);

}

The above code throws ClassCastException during Runtime.

The Object class:

With reference to below code, List<T> cannot be assigned to List<Object>. If allowed, an object of any type could be inserted into the list.

public class GenericIssue2 {

public static void main(String[] args) {

List<Employee> list = new ArrayList<Employee>();

List<Object> olist = list; //compiler error

List list1 = new ArrayList<Employee>(); //Warning: Raw assignment

olist = list1;    //Warning

}

}

class Employee {}

Casting:

Sometimes manual casting required when using generics.

With reference to below code, objects can be added or retrieved into the list, which are treated as Employee.

public class GenericIssue3 {

public static void main(String[] args) {

List<Employee> list = new ArrayList<Employee>();

list.add(new Developer()); //we can add child objects

Developer d = list.get(0); //compiler error

}

}

class Employee {}

class Developer extends Employee {}

Manual casting required as like below

List<Employee> list = new ArrayList<Employee>();

list.add(new Developer()); //we can add child objects

Developer d = (Developer) list.get(0); //Manual casting required

Adding subclasses:

public class GenericIssue4 {

public static void main( String [] args ) {

List<Developer> dlist = new ArrayList<Developer>();

dlist.add(new Developer());

List<Tester> tlist = new ArrayList<Tester>();

tlist.add(new Tester());

List<Employee> elist = new ArrayList<Employee>();

elist.add(new Developer());//type casting required when retrieved.

elist.add(new Tester());//type casting required when retrieved.

elist.addAll(dlist); //add any subclasses of Employee

elist.addAll(tlist); //add any subclasses of Employee

System.out.println(elist);

}

}

class Employee {}

class Developer extends Employee {}

class Tester extends Employee {}

Using subclasses:

List<Employe> list = new ArrayList<Employe>();

List<Object> olist = list; //compiler error

User wildcard syntax here: ?

List<Employe> list = new ArrayList<Employe>();

List<? extends Object> olist = list; //works now!!

Bounded types and wildcards:

See the below code, specially Sum class

 

public class GenericBoundedDemo {

public static void main(String[] args) {

Integer intArray[] = new Integer[] {1,2,3,4,5};

Sum<Integer> si = new Sum<Integer>(intArray);

System.out.println(si.getSumTotal());

Float flotArray[] = new Float[] {20.0f, 30.0f};

Sum<Float> sf = new Sum<Float>(flotArray);

System.out.println(sf.getSumTotal());

}

}

class Sum<T extends Number> {

T [] numberArray;

Sum(T[] objArray) {

numberArray = objArray;

}

double getSumTotal() {

double result = 0.0;

for(T t : numberArray) {

result = result + t.doubleValue();

}

return result;

}

}

Output:

15.0

50.0

Here the Sum class is bound by Number.  The object of type T can call any method of Number.

The objective of this program is, I want a generic class which gives the sum of array of numbers of any type. The result of total must be in double.

Java wildcard element <?> specifies an unknown type.  We can write a generic method that can accept any type of object.

See the revised code below, added a generic Compare method

public class GenericBoundedDemo {

public static void main(String[] args) {

Integer intArray[] = new Integer[] {1,2,3,4,5};

Sum<Integer> si = new Sum<Integer>(intArray);

System.out.println(si.getSumTotal());

Float flotArray[] = new Float[] {20.0f, 30.0f};

Sum<Float> sf = new Sum<Float>(flotArray);

System.out.println(sf.getSumTotal());

System.out.println( si.Compare(sf) );

}

}

class Sum<T extends Number> {

T [] numberArray;

Sum(T[] objArray) {

numberArray = objArray;

}

double getSumTotal() {

double result = 0.0;

for(T t : numberArray) {

result = result + t.doubleValue();

}

return result;

}

String Compare(Sum<?> ob) { //accepts any type of Sum object

if(this.getSumTotal() > ob.getSumTotal())

return “greater”;

else if(this.getSumTotal() < ob.getSumTotal())

return “smaller”;

else

return “equal”;

}

}

Wildcard element acts on collection and which is the supertype of all kinds of collections. The wildcard element itself can be bounded as like below,

String Compare(Sum<? extends Number> ob) {

if(this.getSumTotal() > ob.getSumTotal())

return “greater”;

else if(this.getSumTotal() < ob.getSumTotal())

return “smaller”;

else

return “equal”;

}

Advertisements

3 Comments

  1. Posted October 19, 2012 at 8:26 am | Permalink | Reply

    I always was concerned in this topic and still am, thank you for putting up.

  2. Posted June 6, 2013 at 9:14 am | Permalink | Reply

    I’d like to thank you for the efforts you have put in penning this website. I am hoping to check out the same high-grade content by you later on as well. In fact, your creative writing abilities has encouraged me to get my own, personal site now 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: