Wednesday 6 May 2015

Array List

Array List
  • Java Array List class uses a dynamic array for storing the elements.
  • It extends Abstract List class and implements List interface.
  • Can contain duplicate elements.
  • Maintains insertion order.
  • Non synchronized.
  • Allows random access because array works at the index basis.
  • Manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

Array list declaration ,

Before 1.5 JDK, ArrayList list=new ArrayList();//creating old non-generic array list  

In 1.5 JDK, ArrayList<String> list=new ArrayList<String>();//creating generic array list 

Example,
 ArrayList<String> colorsList =new ArrayList<String>();//creating array list  
 colorsList .add("Red");//adding object in array list  
 colorsList .add("Yellow");
 colorsList .add("Green");

//Print data using Iterate   Iterator itr=al.iterator();//getting Iterator from array list to traverse elements 
 while(itr.hasNext()){  
        System.out.println(itr.next());  
}  

//Print data using enhanced for loop,
for(String obj : colorsList)
    System.out.println(obj); 
 }  

Output : Red,Yellow,Green

Live Examples

Where we have use array list ?
  • To store specified objects
  • To Store growable objects
  • To store custom objects (Student details ex : new ArrayList<Student>() )
Important methods,
addAll,removeAll() and retainAll();

No comments:

Post a Comment