Sunday, September 13, 2009

Simple scenarios with Java generics

A prominent feature added in Java 5.0 is “generics” which enables a programmer to write more type-safe code (code that is tied to specific expected type.. so that no surprises occur at run-time). can say that an API/ code utilizes “generics” when you see strange angle brackets i.e. <> in its method signatures/ class declarations.
Java compiler makes use of a technique called “Type Erasure” to erase the information related to type parameters so that the binary form maintains compatibility with old API (before generics)
You can see that collection framework in Java 5.0 heavily utilizes “generics”
Listed are the simple scenarios where we use generics in day-to-day programming
Scenario#1 :
Declare variables of generic types and instantiate generic type classes (like ArrayList,HashMap,TreeSet,Iterator)

List<String> names = new ArrayList<String>();
/* This guarantees that the items in “names” are always instances of java.lang.String as your code expects.
This enables you to run a for loop and traverse through the list without a class casting */

ArrayList<Car> listForAnyCar=new ArrayList<Car>();
listForAnyCar.add(new Ferrari());
listForAnyCar.add(new Camry());

In the given list you can add any type of Car i.e any class that extends the class Car.

Scenario#2: Pass generic type collections to methods.
You can declare that a method expects generic type collections as argument.

public void takeOnlyListOfStrings(List<String> strings)
for(String astring: strings)
System.out.println(“One of the string is”+astring);

Example# 4:
public void updateListOfCars(List<Car> allCars)
allCars.add(new HondaAccord());

Write generic methods
A generic method means that the method declaration uses a type parameter in its signature.

public <U> boolean inspectTheList(U u) {
return allCars.contains(u);

This method intakes any object and checks if the list allCars contains the object .
This method can further improved to add some more constraints.

public <T extends Number> boolean inspectTheList(T t)
----This signature declares that method inspectTheList can take only objects of type or subtypes of Number

public <T extends Comparable> boolean inspectTheList(T t)
---This signature declares that method inspectTheList can take only objects that implements Comparable..Yes… extends in generics means extends/implements

public <T extends Comparable & Serializable> boolean inspectTheList(T t)
---This signature declares that only objects that implements Serializable AND Comparable can be passed as parameters.

Here are some points you should be aware while declaring and using generic type collections.
1. ArrayList<Car> allCar = ArrayList<HondaAccord>(); // gives compilation error
2. ArrayList<Car> allCar = ArrayList<Car>;//compiles successfully.So compiler won’t bother if this list takes HondaAccord or Ferrari but it should be a Car.

No comments:

Post a Comment