Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. Rich Cook

ArrayList

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 19:48:18

0 Comments


Definition

ArrayList is a resizable array implementation of the ordered collection.

Character

ArrayList is index based and permits null.
It does not support synchronization which cannot be accessed using multiple threads.
It can throw ConcurrentModificationException.
The fail-fast behavior of iterators should be used only to detect bugs.
It takes more memory to store the element and link to the next node compare than Array List.

source Code

								
package com.careerdrill.collections.list;

import java.util.ArrayList;
import java.util.List;

public class ArrayListUse {

	public static void main(String[] args) {

	      List< Integer > al = new ArrayList< Integer >();
	      System.out.println("Initial size of Array List: " + al.size());

	      al.add(11);
	      al.add(22);
	      al.add(33);
	      al.add(44);
	      al.add(55);
	      al.add(66);
	      al.add(1, 77);
	      System.out.println("Size of Array List after additions: " + al.size());
	      System.out.println("Elements from Array List : " + al.toString());


	      System.out.println("Contents of Array List: " + al);

	      
	      al.remove(new Integer(77));
	      al.remove(2);
	      System.out.println("Size of Array List after deletions: " + al.size());
	      System.out.println("Contents of Array List: " + al);

	}

}
						

Output

    					 
Initial size of Array List: 0
Size of Array List after additions: 7
Elements from Array List: [11, 77, 22, 33, 44, 55, 66]
Contents of Array List: [11, 77, 22, 33, 44, 55, 66]
Size of Array List after deletions: 5
Contents of Array List: [11, 22, 44, 55, 66]
    					 
					    

Comparison

LinkedList ArrayList
Linked list search operation is slower than array list. ArrayList search operation is pretty fast compared to the LinkedList.
LinkedList element addition and deletion is faster compared to ArrayList. Array List takes more time for inserting and deleting the elements.
LinkedList has more memory overhead than ArrayList. ArrayList has less memory overhead compare than LinkedList.
Internally uses dynamic array. Internally uses doubly linked list.
Linked list uses links and no need adjust index. ArrayList need to adjust the indexes according to deletion or insertion.

When to use

When you want more search operation rather than insertion and deletion middle of the list, you can use array list.

0 Comments



Please login to add comments.