ArrayList in Java

ArrayList class in collections framework implements the List interface.It gives an ordered collection by index number . But it is not sorted.In the case of ArrayList iteration is faster when compared with LinkedList(Another class that implements List interface). But insertion and deletion are slow in ArrayList.

Now let us see an example code that inserts few items into an ArrayList , then iterates it and finally deletes the items from the list.

public class ArrayListSample {
private ArrayList list = null;
public ArrayListSample() {
list = new ArrayList();
public void addItemsToList() {
String[] listItems = {"dog", "cat", "cow", "elephant", "sheep"};
for (int i = 0; i < listItems.length; i++) { list.add(listItems[i]); } } public void displayList() { System.out.println("Displaying contents of list"); for (String item : list) { System.out.println("Item = " + item); } } public void removeItems() { System.out.println("Removing contents of list"); list.remove("dog"); list.remove("cat"); list.remove("cow"); list.remove("elephant"); list.remove("sheep"); System.out.println("Contents removed ,now size of arraylist = " + list.size()); } public static void main(String[] args) { ArrayListSample sample = new ArrayListSample(); sample.addItemsToList(); sample.displayList(); sample.removeItems(); } }

An item can be added to  an ArrayList using the add() ,ethod.Deletion can be done using delete() method.Now let us see the output.


  Displaying contents of list

Item = dog

Item = cat

Item = cow

Item = elephant

Item = sheep

Removing contents of list

Contents removed  ,now size of arraylist = 0

ArrayList Vs LinkedList

Both implements the List interface.ArrayList is based on index but it is not sorted.LinkedList is also based on index ,but items in LinkedList are doubly linked to each other.Iteration is faster in ArrayList.Deletion and insertion are faster in LinkedList. ArrayList implements the marker interface 'RandomAccess', but LinkedList is not implementing it.LinkedList implements Queue interface (from Java 5 onwards). But ArrayList is not implementing Queue interface.

Tagged with 

One thought on “ArrayList in Java

  1. […] a)ArrayList :ArrayList implements  List interface. It implements the marker interface randomAccess too.ArrayList gives faster iteration.Since it is implementing RandomAccess it provides faster random access too. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">