Java Generics

Generic means parameterized types. The type upon which a generic method, class or interface operates is specified as a parameter. Generics in java permits in application to create classes and object that can operate on any defined types and it also provide a mechanism for annotating type information of generics. We can implement generics by using type erasure. That is the generic information’s are available only at compile time and not translated into the compiled bytes.. Generics are similar to C++ template. They are also helps the compiler to remove the casting errors.

The java generic program feature is unfamiliar to most of the programmers. Generics are new to JDK1.5.  The generic helps to avoid unnecessary casting when dealing with objects in a collection. Generic programming can achieved through type parameters as opposed to inheritance. The various classification of java generics are,

1)      Type variable: – It is an unqualified identifier. These variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.

Eg: –

public static void drawAll(Collection<Shape> shapes) {
for ( Shape s : shapes )
s.draw();
}

2)      Class: – It is a generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.

Syntax: –

public class GenericFactory<E> { }

Eg: –

public class Entry<K, V> {
private final K key;
private final V value;
public Entry(K k,V v) {
key = k;
value = v;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public String toString() {
return “(“ + key + “, “ + value + “)”;
}
}

3)      Interface: – It is also a generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.

Syntax: –

 public interface List<T> extends Collection<T> {
….
}

Eg: -view plaincopy to clipboardprint?

interface ClassA<T>{
public void add(T t);
}
public class Box implements ClassA<Integer> {
int t;
public void add(Integer t) {
this.t = t;
}
public int get() {
return t;
}
}
public class Main {
public static void main(String[] args) {
Box a=new Box();
a.add(10);
System.out.print(a.get());
}
}

4)      Method: – Method is a generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface. Rules for defining generic methods.

1)      All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method’s return type.

2)      Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

3)      The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

4)      A generic method’s body is declared like that of any other method. Note that type parameters can represent only reference type’s not primitive types like int, double and char.

Syntax: –

public static < E > void printArray( E[] inputArray )

Eg: –

class Collections {
public static <A extends Comparable<A>> A max(Collection< A > xs) {
Iterator< A > xi = xs.iterator();
A w = xi.next();
while (xi.hasNext()) {
A x = xi.next();
if (w.compareTo(x) < 0) w = x;
}
return w;
}
}

5)      Constructor: – It can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic. Methods and constructors can be generic if they declare one or more type variables.

Syntax: – public static <t> T getFirst(List <T> list)

Eg: –

<T> NonGeneric(T[] blank, List<T> list) {
// Sort that list
T[] array = list.toArray(blank);
Arrays.sort(array);
// Pull out the values as strings
this.list = new ArrayList<String>(array.length);
for (T value : array) {
this.list.add(value.toString());
}
}

Advantages of java generics

  1. It is a powerful extension to the java language. Because they streamline the creation of type safe, reusable code.
  2. In generics automatic casting and type converting are provided by the compiler.
  3. The collections framework has been entirely reworked.
  4. Generics provide backward compatibility by enabling generic types to be used without type variables.
  5. Can achieve the polymorphic behavior.
  6. Generics are desirable. We can write code that is safer and easier to read than code that is littered with object variables and casts.