How to Java programming- Java ArrayList

Java ArrayList class uses a dynamic array for storing the elements.It extends the AbstractList class and implements List interface. It can contain duplicate elements. Java ArrayList class maintains insertion order and it is non-synchronized. Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
ArrayList allows random access because array works at the index basis. In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.

Java ArrayList
	import java.util.*;
	public class ArrayListExample{

	   public static void main(String args[]) {
		  // create an array list
		  ArrayList al = new ArrayList();
		  System.out.println("Initial size of al: " + al.size());

		  // add elements to the array list
		  al.add("C");
		  al.add("A");
		  al.add("E");
		  al.add("B");
		  al.add("D");
		  al.add("F");
		  al.add(1, "A2");
		  System.out.println("Size of al after additions: " + al.size());

		  // display the array list
		  System.out.println("Contents of al: " + al);

		  // Remove elements from the array list
		  al.remove("F");
		  al.remove(2);
		  System.out.println("Size of al after deletions: " + al.size());
		  System.out.println("Contents of al: " + al);
	   }
	}

 

Output
	Initial size of al: 0
	Size of al after additions: 7
	Contents of al: [C, A2, A, E, B, D, F]
	Size of al after deletions: 5
	Contents of al: [C, A2, E, B, D]

 

Methods of ArrayList class.

ArrayList defines the following methods.

ArrayList MethodDescription
add( Object o)This method adds an object o to the arraylist.
add(int index, Object o)It adds the object o to the array list at the given index.
remove(Object o)Removes the object o from the ArrayList
remove(int index)Removes element from a given index.
set(int index, Object o)Used for updating an element. It replaces the element present at the specified index with the object o.
int indexOf(Object o)Gives the index of the object o. If the element is not found in the list then this method returns the value -1.
Object get(int index)It returns the object of list which is present at the specified index.
int size()It gives the size of the ArrayList – Number of elements of the list.
boolean contains(Object o)It checks whether the given object o is present in the array list if its there then it returns true else it returns false.
clear()It is used for removing all the elements of the array list

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...