ArrayList Class in Java Collection Framework

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

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.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

ArrayList class
  • ArrayList class extends AbstractList class and implements the List interface.
  • ArrayList supports dynamic array that can grow as needed. ArrayList has three constructors.
//constructor builds an empty array list
ArrayList()
//The following constructor builds an array list that is initialized with the elements of the collection c.
ArrayList( Collection C )
/*The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements.

The capacity grows automatically as elements are added to an array list.*/
ArrayList( int capacity )
  • ArrayLists are created with an initial size, when this size is exceeded, it gets enlarged automatically.
  • It can coontain Duplicate elements and maintains the insertion order.
  • ArrayLists are not synchronized.

Methods in the ArrayList Class:
Apart from the methods inherited from its parent classes, ArrayList defines following methods:
SNMethods with Description
1void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2boolean add(Object o) 
Appends the specified element to the end of this list.
3boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
4boolean addAll(int index, Collection c) 
Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5void clear() 
Removes all of the elements from this list.
6Object clone() 
Returns a shallow copy of this ArrayList.
7boolean contains(Object o) 
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8void ensureCapacity(int minCapacity) 
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
9Object get(int index) 
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
10int indexOf(Object o) 
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
11int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
12Object remove(int index) 
Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13protected void removeRange(int fromIndex, int toIndex) 
Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
14Object set(int index, Object element) 
Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
15int size() 
Returns the number of elements in this list.
16Object[] toArray() 
Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
17Object[] toArray(Object[] a) 
Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
18void trimToSize() 
Trims the capacity of this ArrayList instance to be the list's current size.


Example of ArrayList:
import java.util.*;

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

      // add elements to the array list
      list.add("Dinesh");
      list.add("Sweety");
      list.add("Adesh");
      list.add("Vinesh");
      list.add("Mom");
      list.add("DAD");
      
      System.out.println("Size of list after additions: " + list.size());

      // display the array list
      System.out.println("Contents of list: " + list);
     
       System.out.println("Iterating list");
       Iterator itr = list.iterator();
       while(itr.hasNext()){
           System.out.println(itr.next());
       }
   }
}
output:
Two ways to iterate the elements of collection:
  1. By Iterator interface.
  2. By for-each loop.

Iterating the elements of Collection by for-each loop:
import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList list = new ArrayList();
      
      // add elements to the array list
      list.add("Dinesh");
      list.add("Sweety");
      list.add("Adesh");
      list.add("Vinesh");
      list.add("Mom");
      list.add("DAD");
      System.out.println("Iterating list using for each loop");
      for(Object obj : list){
           System.out.println(obj);
      }
   }
}
output:
Storing User-Defined classes:
In the above example we are storing only string object in ArrayList collection. But You can store any type of object, including object of class that you create in Collection classes.
Example of storing User-Defined object

Employee class
class Employee
{
    String firstName;
    String lastName;
    String phone;

    public Employee(String firstName,String lastName,String phone) 
    {
        this.firstName = firstName ;
        this.lastName = lastName;
        this.phone = phone;
    }
    
    public String toString()
    {
        return firstName +" "+lastName +" ("+phone +") ";
    }
}
Storing Employee class
public class EmployeeListDemo
{
    
   public static void main(String[] args) 
   {
       Employee e1 = new Employee("Dinesh", "Rajput","999100091");
       Employee e2 = new Employee("Sandeep", "Sharma","998392819");
       Employee e3 = new Employee("Vinesh", "Kohli","998131319");
       
      ArrayList al = new ArrayList(); 
      al.add(e1);
      al.add(e2);
      al.add(e3);
      System.out.println(al);
   }
    
}
output:
Example of addAll(Collection c) method:
import java.util.*;
class SimpleListDemo{
 public static void main(String args[]){
 
  ArrayList al = new ArrayList();
  al.add("Dinesh");
  al.add("Anamika");
  al.add("Sweety");
  
  ArrayList al2 = new ArrayList();
  al2.add("Adesh");
  al2.add("Vinesh");
  
  al.addAll(al2);  

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}
output:

Example of removeAll() method:
import java.util.*;
class SimpleListDemo{
 public static void main(String args[]){
 
  ArrayList al = new ArrayList();
  al.add("Dinesh");
  al.add("Anamika");
  al.add("Sweety");
  
  ArrayList al2 = new ArrayList();
  al2.add("Anamika");
  al2.add("Vinesh");

  al.removeAll(al2);  

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}
output:

Example of retainAll() method:
import java.util.*;
class SimpleListDemo{
 public static void main(String args[]){
 
  ArrayList al = new ArrayList();
  al.add("Dinesh");
  al.add("Anamika");
  al.add("Sweety");
  
  ArrayList al2 = new ArrayList();
  al2.add("Anamika");
  al2.add("Vinesh");
  System.out.println("iterating the elements after retaining the elements of al2...");
  al.retainAll(al2);  

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}
output:



<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment