ArrayList in java


In this Collection framework tutorial we will learn what is java.util.ArrayList in Collection framework in java.



Contents of page :
  • What is hierarchy of ArrayList in java?
  • ArrayList in java
  • Creating ArrayList in java
  • Add element in ArrayList in java
  • Remove element from ArrayList in java
  • Get element from ArrayList in java
  • Size of ArrayList in java
  • Set element in ArrayList in java
  • Iterate over elements in ArrayList using iterator()
  • Iterate over elements in ArrayList using listIterator()
  • Iterate over elements in list using enumeration
  • Iterate over elements in list using enhanced for loop
  • Some other important methods
  • synchronizing ArrayList in java
  • Complexity of methods in ArrayList
  • Features of ArrayList  in java
  • When to use ArrayList in java



What is hierarchy of ArrayList in java?
-java.lang.Object
-java.util.AbstractCollection
 -java.util.AbstractList
  -java.util.ArrayList


For more detailed hierarchy information read : List hierarchy in java


java.util.ArrayList
java.util.ArrayList is Resizable-array implementation of the java.util.List interface. As ArrayList uses array it is index based structure in java.

java.util.ArrayList implements RandomAccess(Marker interface) to indicate that they support fast random access (i.e. index based access) in java.

java.util.ArrayList extends AbstractList (abstract class) which provides implementation to  List interface to minimize the effort required to implement this interface backed by RandomAccess interface in java.





Creating java.util.ArrayList
creates array with initial capacity of 10 in java.
List<String> arrayList=new ArrayList<String>();
Defining ArrayList<String> means list can be used to store only String types, storing any other type will cause compilation error.


Add element in java.util.ArrayList
add(E element)
Adds specified element in ArrayList in java.

arrayList.add("ankit");    
Will insert “ankit” in arrayList.


add(int index, E element)
Adds specified element in Array List at specified index.

arrayList.add(1, "javaMadeSoEasy");    
Will insert “javaMadeSoEasy” at first index.

Null can be added in ArrayList.
While adding, if array becomes full, it is restructured, it’s capacity is increased to 15 in java.



Remove element from java.util.ArrayList
remove(int index)
Removes element on specified index.

   arrayList.remove(1);
Removes element on first index in java.

remove(Object object)
Removes first occurrence of specified object.

arrayList.remove("ankit");
Removes first occurrence of “ankit



Get element from java.util.ArrayList
get(int index)
Method returns element on specified index.

arrayList.get(2);
Method returns element on 2nd index.
         

Size of java.util.ArrayList
size()
Method returns size of ArrayList.

System.out.println(arrayList.size());
will print size of arrayList.


Set element in java.util.ArrayList
set(int index, E element)
Method sets specified element at specified index.
Set method replaces the element at the specified index in this list with the specified element.



Iterate over elements in java.util.ArrayList using iterator()
iterator() method returns iterator to iterate over elements in ArrayList in java.
Iterator important methods :
hasNext() method returns true if the iteration has more elements. (Traversing/Iteration is  done in forward direction).
next() method - returns next element in iteration.
if the iteration has no more elements than NoSuchElementException is thrown.
remove() method - removes last element returned by iterator.
Method must always be called after call to next() method else IllegalStateException is thrown.

code-
    Iterator<String> iterator=arrayList.iterator();
   while(iterator.hasNext()){
          System.out.println(iterator.next());
   }


iterator returned by java.util.ArrayList is fail-fast. Means any structural modification made to ArrayList like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
Removing element by using iterator is allowed.

code-
    Iterator<String> iterator=arrayList.iterator();
   while(iterator.hasNext()){
          System.out.println(iterator.next());
             arrayList.add("ind");    
   }
Element has been added during iteration which will cause ConcurrentModificationException to be thrown.


Iterate over elements in ArrayList using listIterator()
listIterator method returns listIterator to iterate over elements in ArrayList.
ListIterator important methods :
Apart from hasNext(), next() and remove() methods provided by Iterator, ListIterator additionally provides -
hasPrevious()  method returns true if this listIterator has more elements when traversing the list in the reverse direction in java.
previous()  returns previous element in iteration (traversing in backward direction).
if the iteration has no previous elements than NoSuchElementException is thrown in java.

nextIndex()  method returns the index of the element that would be returned by a subsequent call to next() method. If listIterator is at the end of the list than method returns size of list in java.

previousIndex()  method returns the index of the element that would be returned by a subsequent call to previous() method. If listIterator is at the start of the list than method returns -1 in java.

add(E element)
Method inserts the specified element into the list.
The element is inserted immediately before the element that would be returned by next (So, subsequent call to next would be unaffected), if any, and after the element that would be returned by previous (So,subsequent call to previous would return the new element), if any.
If the list does not contain any element than new element will be the sole element in the list in java.

set(E element)
Method replaces the last element returned by next() or previous() method with the specified element. This call can be made only if neither remove nor add have been called after the last call to next or previous.
If call to set() method is followed up by any call made to remove() or add() method after next() or previous() than UnsupportedOperationException is thrown in java.

ListIterator returned by ArrayList is also fail-fast. Means any structural modification made to ArrayList during Iteration will throw ConcurrentModificationException in java.
-set method does not cause structural modification, because size of list remains same.

ListIterator<String> listIterator=arrayList.listIterator();



Iterate over elements in list using enumeration
  Enumeration<String> listEnum=Collections.enumeration(arrayList);
   while(listEnum.hasMoreElements()){
      System.out.println(listEnum.nextElement());
   }
enumeration is also fail-fast.




Iterate over elements in list using enhanced for loop
          for (String string : arrayList) {
             System.out.println(string);
      }
enhanced for loop is also fail-fast.



Some other important methods of java.util.ArrayList>
toArray() method converts and returns all elements of list in array. (Sequence of elements is maintained)

isEmpty() method returns true if this list contains no elements in java.

clear() method removes all elements from list in java.


synchronizing java.util.ArrayList
We can synchronize arrayList by using Collections’s class synchronizedList method.
List synchronizedList = Collections.synchronizedList(arrayList);
Now, no 2 threads can access same instance of list concurrently.



Complexity of methods in java.util.ArrayList
Operation/ method
Worst case
Best case
add
O(n), when array is full it needs restructuring,
operation runs in amortized constant time.
O(1), when array does not need any restructuring.
remove
O(n), when removal is done from between restructuring is needed.
O(1), when removal is done at last position, no restructuring is needed.
get
O(1), it is index based structure. So, complexity of  get operation is always done in O(1).
O(1) it is index based structure. So, complexity of  get operation is always done in O(1).
set
O(1), it is index based structure, no restructuring is needed in set operation. So, complexity of operation is always O(1)
O(1), it is index based structure, no restructuring is needed in set operation. So, complexity of operation is always O(1)
iterator
O(n), because iteration is done over each and every element.
O(n), because iteration is done over each and every element.
listIterator
O(n), its same as iterator.
O(n), its same as iterator.
enumeration
O(n), its same as iterator.
O(n), its same as iterator.



Features of java.util.ArrayList
  1. ArrayList  is Resizable-array implementation of the java.util.List interface in java

  1. Index based structure - ArrayList is an Index based structure in java.

  1. Duplicate elements - ArrayList allows to store duplicate elements in java.

  1. Null elements -Null elements can be added in ArrayList in java.
  2. Insertion order - ArrayList maintains insertion order in java.
Example in java-
Let’s say we add 3 elements in arrayList
arrayList.add("ind");    
arrayList.add("aus");    
arrayList.add("sa");

On displaying insertion order will be maintained i.e.
ind
aus
sa


  1. synchronized - It is not synchronized (because 2 threads on same ArrayList object can access it at same time).

  1. Performance - ArrayList is not synchronized, hence its operations are faster as compared to some other synchronized implementation of List interface in java.

  1. implements RandomAccess - (ArrayList implements RandomAccess(Marker interface) to indicate that they support fast random access (i.e. index based access) in java.

  1. extends AbstractList - ArrayList extends AbstractList (abstract class) which provides implementation to  List interface to minimize the effort required to implement this interface backed by RandomAccess interface.


When to use java.util.ArrayList
  1. ArrayList can be used when we want to store duplicate elements in java.

  1. ArrayList can be used when we want to store null in java.

  1. We must prefer ArrayList for when add and remove operations are less as compared to get operations, and

  1. ArrayList can be used when we are not working in multithreading environment in java.



So in this Collection framework tutorial we learned what is java.util.ArrayList in Collection framework in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

Basic Collection >

Collection in java

List hierarchy in java - Detailed - ArrayList, LinkedList, vector, CopyOnWriteArrayList classes


List >

ArrayList in java


LinkedList in java






Consequence and advantage of using ArrayList and Vector in multithreading environment >

Consequence of using ArrayList in multithreading environment in java

Advantage of using Vector in multithreading environment in java


ArrayList Programs >
ArrayList - add, add element at specific index methods program


ArrayList - remove, get, contains and set methods program


ArrayList - iterate using iterator, listIterator, Enumeration and enhanced for loop


ArrayList - fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop


ArrayList - isEmpty, size and clear methods program


ArrayList - synchronizing using Collections.synchronizedList


ArrayList - making list unmodifiable using Collections.unmodifiableList


Different approaches/Programs to Sort List >
Program to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method


Program to sort Employee list on basis of name in ascending order by implementing Comparator interface and overriding its compare method


Program to sort Employee list on basis of name and id in ascending order by implementing Comparator interface and overriding its compare method


Program to sort Employee list on basis of name and id in ascending order by implementing Comparator interface in inner and static inner class and overriding its compare method




No comments:

Post a Comment