ArrayList in java

  • Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class and implements List interface
  • An object of ArrayList class represent an dynamic array.
  • ArrayList is not thread safe that is all method of ArrayList is not synchronized.
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList allows random access because array works at the index basis.
  • ArrayList class provide implementation of List interface through AbstractList class.
  • ArrayList use Iterator or ListIterator to traversing elements.

Syntax :- ArrayList arrlist=new ArrayList

Note :Array list default initial capacity is 10. we can also mention the capacity at the time of creating ArrayList object.

Example of Java ArrayList class


  import java.util.*; 

	class DemoArrayList{ 

	public static void main(String args[]){ 

	ArrayList al=new ArrayList();//creating arraylist 

	al.add("Ram");//adding object in arraylist 

	al.add("Ravi"); 

	al.add("Neha"); 

	al.add("Mithi");	

	Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements 

	while(itr.hasNext()){ 

	System.out.println(itr.next()); 

	} 

	} 

	} 

 
				
				
				
				
						
						
						
						
						
						

Output


 Ram

 Ravi

 Neha 

 Mithi

 

Another Example of ArrayList


import java.util.ArrayList;

import java.util.Collections;

public class ArrayListDemo{

	String name;

	String address;

	Integer id;

	public ArrayListDemo

		(String name,String address, int id){

		this.name=name;

		this.address=address;

		this.id=id;

	}

	public String toString(){

		return "name = "+name+" address "+address+" id = "+id;

	}

	public static void main(String[] args) {

		ArrayListDemo a1 =new ArrayListDemo("tkhts","UK",25000);

		ArrayListDemo a2 =new ArrayListDemo("techknow","USA",35000);

		ArrayList list=new ArrayList();

		list.add(a1);

		list.add(a2);

		System.out.println(list);

	}

}

	}

}

Output


name=tkhts address=US id=25000

name=techknow address=USA id=35000

Your can create two type iterate the elements of collection in java

  1. By Iterator interface.
  2. By for-each loop.