Generics Java Tutorial

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.

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.

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)

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

One thought on “Generics Java Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *