Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday, 9 June 2016

Generics in Java

Hello friends,

What is Generics:-

In Generics we can store any type of objects in collection but non-generic we  store only specific type of object.

In generic not need to type casting.But non-generic compulsory to type casting like..

List mylist=new ArrayList();
mylist.add("Samset"); 

String str=(String)mylist.get(0);     //This is typecasting


List<String> mylist=new ArrayList(String);
mylist.add("Samset"); 

String str=mylist.get(0);     //No need typecasting

Example.java

public class Test
{
public static void main(String ar[])
{
List<String> mylist=new ArrayList(String);
mylist.add("Hello"); 
mylist.add("Samset"); 


for(int i=0;i<mylist.size();i++)
{
System.out.println("String data :- "+mylist.get(i));
}
}
}

OUTPUT :- 
String data :-

Hello
Samset


Second Example 


public class Test2
{
   // generic method printArray                         
   public static < E > void printArray( E[] input )
   {
      // Display array elements              
         for ( E element : input ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'W', 'E', 'L', 'C', 'O','M','E' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}


OUTPUT :-


Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 

Array characterArray contains:
W E L C O M E