Generics Java Tutorial


The main difference between arrays and data structures is array accepts only one type of data and data structure accepts elements of dissimilar data types. See the following code of ArrayList accepting dissimilar data type values.

import java.util.ArrayList;
import java.util.Date;

public class Demo
{
  public static void main( String args[])
  {
    ArrayList al = new ArrayList();                       // non Generics Java
                                                          // ArrayList can store any type of data
    al.add(50);                                           // int value
    al.add(80.5);                                         // double value
    al.add("Hello");                                      // String object
    al.add(new Date());                                   // Date object

    System.out.println(al);
  }
}

Generics Java

The above compiles and runs successfully and can be seen in the above screen output. But the compiler raises a warning of unchecked and unsafe operations. One more observation is the code is compiled with JDK 1.7.

From JDK 1.5 onwards, Java allows a DS to store only one type of data, say, integers, doubles, String objects, Date objects or Employee objects. This feature added in JDK 1.5 is known as Generics. Now observe the following ArrayList objects that allow to add only ints or Strings.

import java.util.ArrayList;

public class Demo
{
  public static void main( String args[])
  {
    ArrayList al1 = new ArrayList();  // stores only int values
    al1.add(50);  
    al1.add(60);  
    al1.add(70);  
    System.out.println(al1);

    ArrayList al2 = new ArrayList(); // stores only String values
    al2.add("Hello");
    al2.add("World");
    al2.add("Thanks");
    System.out.println(al2);
  }
}

image

Two generic objects of ArrayList al1 and al2 are created storing only int values and String values. Now observe, the compiler does not raise a warning message because we are doing a safe operation of checking the input. This type safe checking operation (known as Generics) helps in realtime a lot. For example, a software asks the teacher to give the roll numbers of students that did not pay the fees. The input for the program is taken from keyboard. If the teacher adds by mistake a roll number of 25.5, the compiler raises error; the same in C/C++, should be checked with extra code.

Let us go a little bit deeper where ArrayList stores only Employee objects (Generics Java storing Employee objects)
import java.util.ArrayList;
public class Employee
{
  String name;
  int salary;
  public Employee(String name, int salary)
  {
    this.name = name;
    this.salary = salary;
  }
  public String toString()
  {
    return name + " : " + salary;
  }
  public static void main(String args[])
  {
    Employee emp1 = new Employee("S N Rao", 9999);
    Employee emp2 = new Employee("Jyostna", 8888);

    ArrayList al = new ArrayList(); // observe, syntax of Generics Java
    al.add(emp1);                                       // while creating generics ArrayList
    al.add(emp2);

    System.out.println(al.get(0));
    System.out.println(al.get(1));
  }
}

Generics Java

A generic ArrayList object al storing only Employee objects is created and added with two Employee objects emp1 and emp2. Later retrieved with get() method overriding toString() method.

Apart generics, two other features added to DS from JDK 1.5 are autoboxing and enhanced for loop.

Read more for comparing and converting different concepts of Java:

1. Java Comparisons (vs)
2. Java Conversions

1 thought on “Generics Java Tutorial”

Leave a Comment

Your email address will not be published.