Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

ArrayList in Java

  • The ArrayList class in Java extends AbstractList and implements List Interface and also allows null.
  • The ArrayList class is a dynamic array that can grow and shrink at runtime.
  • ArrayList class is expandable or re – sizable array and used behalf of array because array is fixed size and cannot modify once we create it.
  • ArrayList allows duplicate elements.
  • ArrayList support both Iterator and ListIterator for iteration purpose.
  • ArrayList is not synchronized and hence it not thread safe.
  • ArrayList support single dimensional and heterogeneous data.

The following table demonstrates the constructors of the ArrayList class and its methods.

Constructor
Meaning
ArrayList
Constructs an Empty ArrayList Object.
ArrayList(Collection c)
Constructs a list containing the elements of the given collection.
ArrayList(int capacity)
Constructs an ArrayList object with the given initial capacity.

The following program shows a simple use of ArrayList. An array list is created, and then objects of type String are added to it. The list is then displayed. 

Example:

/**
 From SimpleArrayList.java
*/

import java.util.ArrayList;
/**
 *
 * @author JavaHotSpot
 */

public class SimpleArrayList
{
  public static void main(String args[])
  {
      ArrayList alist = new ArrayList();
      alist.add("Book1");
      alist.add("Book2");
      alist.add("Book3");
      alist.add("Book4");
      alist.add("Book5");
      alist.add("Book6");
      alist.add("Book7");
      System.out.println("The size of the ArrayList="+alist.size());
      System.out.println("The elements of ArrayList are..."+"\n"+alist);
      alist.remove("Book7");
      System.out.println("The size of the ArrayList after removing single item="+alist.size());
      System.out.println("The elements of ArrayList are..."+"\n"+alist);
  }
}

Output:
The size of the ArrayList=7
The elements of ArrayList are...
[Book1, Book2, Book3, Book4, Book5, Book6, Book7]
The size of the ArrayList after removing single item=6
The elements of ArrayList are...
[Book1, Book2, Book3, Book4, Book5, Book6]