Protected by Copyscape
Powered By Blogger

Monday, August 10, 2015

Generic Collection

Generic collection allows you to have only one type of items in collection.Advantage is that typecasting is not required at run time.

Non generic way of creating a collection:

ArrayList list1=new ArrayList();

New generic declaration
ArrayList<String> list1=new ArrayList<String>();

Example:

import java.util.ArrayList;
import java.util.Iterator;

public class GenericArrayList
{

public static void main(String[] args)
{
ArrayList<String> list1=new ArrayList<String>();
       
  list1.add("Ravi");//adding object in arraylist
  list1.add("Vijay");
  list1.add("Ravi");
  list1.add("Ajay");
 //list1.add(new Integer(10));
    //uncommenting the above will give error.

 //Iterating the elements of Collection by using Iterator interface
 Iterator itr=list1.iterator();
 while(itr.hasNext())
 {
 System.out.println(itr.next());
 }
   

 //Iterating the elements of Collection by for-each loop
 for(String obj:list1)
  {
  System.out.println(obj);
  }

}

}

No comments: