Generic in Java

Introduction to Generic

The Java generic features were introduced in Java 5. It provides the type safety object. It provides the type for methods parameters and return type dynamically by achieving compile time type checking. Generic provides the solution for ClassCastException.
A class, interface, or method that operates on a parameterized type is called generic. The generic expand the ability to reuse code.

Syntax:

class Test<T>
{
     void method1(T t){ }
     <T> method2(){ }
     Test <T>() { }
}


For Example:

ArrayList<String> list = new ArrayList<String>();
List.add("Java");
String str = list.get(0);


Example: Implementing Generic class in Java

import java.util.*;
public class GenDemo
{
    public static void main(String args[])
    {
        ArrayList<String> list = new ArrayList<String>();
        list.add("DigVijay");
        list.add("Surendra");
        list.add("Pravin");
        //list.add(101); compile time error
        Iterator<String> itr = list.iterator();
        while(itr.hasNext())
        {
           String str = itr.next();
           System.out.println("Name: "+str.toUpperCase());
        }
    }
}


Output:
Name: DIGVIJAY
Name: SURENDRA
Name: PRAVIN

Generic Class

A generic class improves the type safety. It can refer to any type of parameter. A generic class declaration followed by a type parameter after the class name. A generic class can have more than one parameters separated by commas.
For creating generic type class, we used T type parameter.

Syntax:

class class_name<type_param_list>
{
     class_name<type_arg_list> var_name = new class_name<type_arg_list>();
}


Example: Using Generic class in Java.

public class Test<T>
{
     private T t;
     public void insert(T t)
     {
     this.t = t;
     }
     public T get()
     {
     return t;
     }
     public static void main(String[] args)
     {
         Test<Integer> in = new Test<Integer>();
         Test<String> str = new Test<String>();
         Test<Float>  fl = new Test<Float>();
    
         in.insert(new Integer(101));
         str.insert(new String("Java"));
         fl.insert(new Float(20.30));
    
         System.out.printf("Integer Value: %d", in.get());
         System.out.printf("\nString Value: %s", str.get());
         System.out.printf("\nFloat value: %f", fl.get());
    }
}


Output:
Integer Value: 101
String Value: Java
Float value: 20.299999
Java Generic Type

Generic type naming convention in Java provides us easy understanding of the code. The most commonly used type parameter names are:

E:  Element
K: Key (used in Map)
N: Number
T:Type
V: Value (Used in Map)

Generic Interfaces

Generic interfaces are specified just like generic classes. Comparable interface is the good example of generic interface.

Example:

import java.util.*;
public interface Comparable<T>
{
    public int compareTo(T  o)
}

Generic Methods

Generic methods introduce their own type parameter. Generic methods can accept any type of parameter. It is possible to create a generic method that is enclosed within a non-generic class.

Example: Illustrating generic methods.

public class GenMethDemo
{
    static <T, V extends T> boolean genMeth(T x, V[] y)
    {
       for(int i = 0; i < y.length; i++ )
           if(x.equals(y[i]))
           {
               return true;
           }
       return false;
    }
    public static void main(String args[])
    {
        Integer arr[] = {1, 2, 3, 4, 5, 6};
        if(genMeth(3, arr))
        {
            System.out.println("3 is present in array");
        }
        if(!genMeth(9, arr))
        {
            System.out.println("9 is not present in array");
        }
        String strs[] = { "Java", "C++", "Oracle", "Python"};
        if(genMeth("Java", strs))
        {
            System.out.println("Java is present in String array");
        }
        if(!genMeth("PHP", strs))
        {
            System.out.println("PHP is not present in String array");
        }
    }
}


Output:
3 is present in array
9 is not present in array
Java is present in String array
PHP is not present in String array

Wildcard in Generics

In Java Generic code, the question mark (?), called the wildcard and represents an unknown type. The wildcard can be used in a type of parameter, field or local variable.

Example:

import java.util.*;
abstract class Vehicle
{
    abstract void speed();
}
class Bike extends Vehicle
{
    void speed()
    {
        System.out.println("Speed of Bike is: 50 Km/h");
    }
}
class Car extends Vehicle
{
    void speed()
    {
        System.out.println("Speed of Car is: 70 Km/h");
    }
}
class Bus extends Vehicle
{
    void speed()
    {
        System.out.println("Speed of Bus is: 60 Km/h");
    }
}
public class GenericDemo
{
    public static void findSpeed(List<? extends Vehicle> lists)
    {
        for(Vehicle v : lists)
        {
            v.speed();
        }
    }
    public static void main(String args[])
    {
         List<Bike> list1 = new ArrayList<Bike>();
         list1.add(new Bike());
    
         List<Car> list2 = new ArrayList<Car>();
         list2.add(new Car());
    
         List<Bus> list3 = new ArrayList<Bus>();
         list3.add(new Bus());
    
         findSpeed(list1);
         findSpeed(list2);
         findSpeed(list3);
    }
}


Output:
Speed of Bike is: 50 Km/h
Speed of Car is: 70 Km/h
Speed of Bus is: 60 Km/h