Generic Programming in Java
Generic Programming in Java
Java
Java Generics
• The Java Generics allows us to create a single class, interface, and method
that can be used with different types of data.
• In other words, Generics is a concept where you can enable a class,
interface and, method, accept all reference types as parameters.
• Java generics is used to achieve parametric polymorphism.
• Generics uses the diamond syntax <Type>.
• Generics in Java is similar to Templates used in C++.
• Generic programming is a style of programming in which algorithms are
written to be specified later types that are instantiated when needed for
specific types provided as parameter.
Generic Classes
class Gen<T> {
private T data;
public Gen (T data) {
this.data = data;
}
public T getData() {
return this.data;
}
}
class Main {
public static void main(String[] args) {
Gen<Integer> intObj = new Gen<Integer>(5);
System.out.println("Class returns: " + intObj.getData());
Gen<String> stringObj = new Gen<Integer>("Java Programming");
System.out.println("Class returns: " + stringObj.getData());
}
}
Generic Class with 2 Parameter
class TwoGen<T, V>{ public class Main {
T ob1; public static void main(String[] args) {
V ob2; TwoGen<Integer, String> Obj1 = new TwoGen<Integer, String>(22, "apple");
TwoGen(T o1, V o2){ TwoGen<Integer, Double> Obj2 = new TwoGen<Integer, Double>(52, 3.14);
ob1 = o1; Obj1.showTypes();
ob2 = o2; Obj2.showTypes();
} int a = Obj2.getob1();
void showTypes(){ System.out.println(a);
System.out.println("Type of T is "+ ob1.getClass()); double b = Obj2.getob2();
System.out.println("Type of V is "+ ob2.getClass()); System.out.println(b);
} }
T getob1(){ }
return ob1;
}
V getob2(){
return ob2;
}
}
Generic Method
public class Main {
public static < E > void printArray( E[] inputArray ) {
for(E element : inputArray) {
System.out.print(element+ " ");
}
System.out.println();
}
class GenConsDemo {
public static void main(String args[]) {
GenСons test = new GenСons (100);
GenСons test2 = new GenСons (123.5F);
test. showval();
test2.showval();
}
}
Wildcard Arguments
• The question mark (?) is known as the wildcard in generic programming
. It represents an unknown type.
• The wildcard can be used in a variety of situations such as the type of a
parameter, field, or local variable; sometimes as a return type.
• We can use a wildcard as a type of a parameter, field, return type, or
local variable.
• It is not allowed to use a wildcard as a type argument for a generic
method invocation, a generic class instance creation.
• There are 3 ways of using wildcard:
• Unbounded - ?
• Upper bounded - ? extends Type
• Lower bounded - ? super Type
Type Erasure
• Generics are used for tighter type checks at compile time and to
provide a generic programming. To implement generic behavior, java
compiler apply type erasure.
• Type erasure is a process in which compiler replaces a generic
parameter with actual class or bridge method. In type erasure,
compiler ensures that no extra classes are created and there is no
runtime overhead.
• Type Erasure rules
• Replace type parameters in generic type with their bound if bounded type
parameters are used.
• Replace type parameters in generic type with Object if unbounded type
parameters are used.
• Insert type casts to preserve type safety.
• Generate bridge methods to keep polymorphism in extended generic types.
public class Node<T> { public class Node {
public Node(T data, Node<T> next) { public Node(Object data, Node next) {
this.data = data; this.data = data;
this.next = next; this.next = next;
} }
public T getData() { return data; } public Object getData() { return data; }
} }
public Node(T data, Node<T> next) { public Node(Comparable data, Node next) {
this.data = data; this.data = data;
this.next = next; this.next = next;
} }
public T getData() { return data; } public Comparable getData() { return data; }
} }
Advantages
• Increases code reusability.
• A Java compiler applies strong type checking to generic
code and issues errors if the code violates type safety.
Fixing compile-time errors is easier than fixing runtime
errors, which can be difficult to find.
• There is no need to typecast the object.
• By using generics, we can implement algorithms that work
on different types of objects and at the same they are type
safe too. The java collection framework that contains data
structures and algorithms implement generics.
//Without Generics – No type safety //With Generics – Type safety
List list = new ArrayList(); List<String> list = new ArrayList<String>();
list.add(10); list.add(“java");
list.add(“abc"); list.add(12.6); //compile time error