Java Generics

Non Generic Code

Generic in java was introduced in java 5.

Before we learn about Generics in java, let us first understand the problem that caused the introduction of generics concept in java.


Lets have a look at the below non-generic code.


package javaRadarArrayList;

import java.util.ArrayList;
import java.util.List;

public class SimpleArrayList {

     public static void main(String[] args) {

      //create Array List
        List javaRadarList = new ArrayList();

       //Add elements to ArrayList

          String index0 = (String)javaRadarList.get(0); //type-casting required
          int index1 = (int)javaRadarList.get(1); //type-casting required




[Java, 10001, 11.1111, C]


Important points to note in non-generics:

From the above code we can observer few important things in non-generic code:


Not type Safe

We can see that there is no restriction to what type of value this list (javaRadarList) holds. 

We have inserted String, int, double, char. So we now know that it is free to hold any data type.

But then the management of this diverse data type values will be difficult task.


Type-casting required

While fetching the value from the list index, we need to type cast the values to their respective data types. See the last two lines before closing braces storing values in index0 and index1.


This is what made introduction of Generics important to let programmars restrict store only specified data type in a list. 

In the next chapter of this java tutorial, we will see how use of Generics provides this restriction.


Please Share this page
Views : 157
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!