Monday 22 July 2013

What is Generics in java?




Arrays in Java have always been type safe. For example, an array declared as type integer can only accept integers (not String, Dog, Cat). But, collections are not like that. There is no syntax for declaring type safe collections before java 5. To create an Collection of a particular type java introduced Generics in java5.

ArrayList Without Generics

ArrayList lst = new ArrayList();

ArrayList With Generics

ArrayList<Integer>  lst = new ArrayList<Integer>();

Example Code:

import java.util.*;

public class demoCollection11
{
    public static void main(String s[])
    {
        System.out.println("ArrayList without Generics");
        ArrayList ar = new ArrayList();
        ar.add(10);
        ar.add(11);
        ar.add(12);
        Object a = ar.get(1);//Before generic it always return the object type
        System.out.println(ar);
        System.out.println("");
        System.out.println("ArrayList with Generics");
        ArrayList<String> ar1 = new ArrayList<String>();
        //ar1.add(10);   This will give error because ar1 list is of String type
        ar1.add("Ten");
        ar1.add("Eleven");
        ar1.add("Twelve");
       
        String str = ar1.get(1); //With generic, You can directly get the value in string type variable
        System.out.println(ar1);
    }
}

Output:

ArrayList without Generics
[10, 11, 12]

ArrayList with Generics
[Ten, Eleven, Twelve]

No comments:

Post a Comment