CodesJava

Easy learning with example program codes

ArrayList in java


ArrayList:

ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.

Note: ArrayList provides the facility of random access because of it is index based.

ArrayList example:

ArrayListSetTest.java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * This class is used to show the ArrayList functionality.
 * @author codesjava
 */
public class ArrayListTest {
	public static void main(String args[]){
		//Create ArrayList object.
		List arrayList = new ArrayList();
 
		//Add objects to the HashSet.
		arrayList.add("Amani");
		arrayList.add("Prabhjot");
		arrayList.add("Nidhi");
		arrayList.add("Vandana");
		arrayList.add("Poonam");
 
		//Size of the ArrayList object.
		System.out.println("Size: " 
				+ arrayList.size());
 
		//Print the ArrayList object.
		System.out.println("ArrayList elements:");
		System.out.println(arrayList);
 
		//Print the ArrayList elements using iterator.
		Iterator iterator1=arrayList.iterator();
		System.out.println("ArrayList elements " +
				"using iterator:");
		while(iterator1.hasNext()){  
		   System.out.println(iterator1.next());  
		} 
 
		//Add an object at the specific position.
		arrayList.add(2,"Jagdeep");
 
		//Remove a element from a specific position.
		arrayList.remove(3);
		arrayList.remove(4);
 
		//Size of the ArrayList object.
		System.out.println("Size after manipulation: "
				+ arrayList.size());
 
		//Print the ArrayList object.
		System.out.println("ArrayList elements" +
				" after manipulation:");
		System.out.println(arrayList);
 
		//Print the ArrayList elements using iterator.
		Iterator iterator2=arrayList.iterator();
		System.out.println("ArrayList elements after" +
				" manipulation using iterator:");
		while(iterator2.hasNext()){  
		   System.out.println(iterator2.next());  
		} 	
	}
}

Output:

Size: 5
ArrayList elements:
[Amani, Prabhjot, Nidhi, Vandana, Poonam]
ArrayList elements using iterator:
Amani
Prabhjot
Nidhi
Vandana
Poonam
Size after manipulation: 4
ArrayList elements after manipulation:
[Amani, Prabhjot, Jagdeep, Vandana]
ArrayList elements after manipulation using iterator:
Amani
Prabhjot
Jagdeep
Vandana

Download this example.
 
Next Topic: ArrayList in java with example.
Previous Topic: LinkedList in java with example.

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki