Generic was introduced in Java 1.5 along with some other features like autoboxing, Enum, varargs and static import. This is mainly used for ensuring the type-safety. Because, in a Generic class, type will be determined at the time of instantiation.

Main benefits.

  1. Parametrized classes offer type verification at the compile time.
  2. If you use Generic parametrized method or class you don’t need to use casting (into a specific type)
  3. Generic methods don’t throw ClassCastException  at the runtime. ( Because, Type verification was already done at compile time)

Writing generic – parametrized classes

Client.java


public class Client {

public static void main(String[] args) {

// Non-generic old approach --------------------------------------------------------------

OldContainer oldStringContainer = new OldContainer();

oldStringContainer.setItem(123); //no compilation error i.e. no type checking at compile time. So it allows to add an int although you created a oldStringContainer to add a String

((String)oldStringContainer.getItem()).toUpperCase(); // Casting is needed and will throw ClassCastException at runtime
// New Generic approach ------------------------------------------------------------------

// String Container
Container<String> stringContainer = new Container<String>();
stringContainer.setItem("Test");
//stringContainer.setItem(new StringBuffer("")); // compilation error, type safety checking

System.out.println(stringContainer.getItem().toUpperCase()); // No need to cast

// Integer Container
Container<Integer> integerContainer = new Container<Integer>();
integerContainer.setItem(123);

System.out.println(integerContainer.getItem().intValue()); // No need to cast

//integerContainer.setItem("123"); // compilation error, type safety checking
}

}

Container<T> class (Generic parameterized class, offers type checking at compile time.)


class Container<T> {

private T item;

public T getItem(){
return item;
}

public void setItem(T item){
this.item = item;
}
}

OldContainer (Non-Generic Class  – fragile and error prone)


class OldContainer{

private Object item;

public Object getItem(){
return item;
}

public void setItem(Object item){
this.item = item;
}

}

Writing parametrized method in Java Generics

Parametrized method in Java accepts method argument as type and/or returns type instead of any particular type like String, Double or Float.
Any static utility method which operate on Object type is good candidate of converting to parametrized or Generic method in Java.


 public static <T> T wrap(T item){
 //code for wrapping item
 return item;
 }

References :

Advertisements