Java util ArrayList Class - ArrayList Class in Java



QR Code for this Page

[pic]

java util ArrayList Class - ArrayList Class in Java

Java ArrayList Tutorial with Examples

ArrayList in Java is used to store dynamically sized collection of elements. Java Arrays are fixed in size, an ArrayList grows its size automatically when new elements are added to it. ArrayList is part of Java's collection framework and implements Java's List interface. Java ArrayList is not synchronized. ArrayList is a part of collection framework and is present in java.util package.

The ArrayList class is the Collection Framework's replacement for the Vector class. Functionally equivalent, their primary difference is that ArrayList usage is not synchronized by default, whereas Vector is. Both maintain their collection of data in an ordered fashion within an array as their backing store.

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

What are the Features of ArrayList in Java ?

• ArrayList inherits AbstractList class and implements List interface.

• An ArrayList is a re-sizable array, also called a dynamic array. It grows its size to accommodate new elements and shrinks the size when the elements are removed.

• ArrayList internally uses an array to store the elements. Just like arrays, It allows you to retrieve the elements by their index.

• Java ArrayList is an ordered collection. It maintains the insertion order of the elements.

• Java ArrayList allows duplicate and null values.

• Java ArrayList is not synchronized.

• You cannot create an ArrayList of primitive types like int, char etc. You need to use boxed types like Integer, Character, Boolean etc.

Is ArrayList Thread Safe ?

The ArrayList implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list.

To prevent accidental unsynchronized access to the list, you should create list with Collections.synchronizedList method.

What is the ArrayList Performance ?

The array provides quick, random access to elements at a cost of slower insertion and deletion of those elements not at the end of the list. If you need to frequently add and delete elements from the middle of the list, consider using a LinkedList.

What are the Similarities found in ArrayList ?

ArrayList shares some similarities with HashSet and TreeSet and provides some behavior that is not the same. The base implementation class is similar to HashSet and TreeSet both extend from the AbstractCollection superclass. However, instead of further extending from AbstractSet, ArrayList extends from AbstractList. Unlike the sets, ArrayList supports storing duplicate elements. While much of the ArrayList behavior is inherited from AbstractList, the class still needs to customize the majority of its behavior.

In this tutorial you can learn about java.util.ArrayList class and its examples. And also learn how to use java.util.ArrayList class.

How do you declare an ArrayList in Java ?

You can declare Java ArrayList as follows.

ArrayList list = new ArrayList(); //Creating arraylist.

The following Java ArrayList Example shows

1. How to declare an ArrayList

2. How to create an ArrayList using the ArrayList() constructor.

3. How to Add new elements to an ArrayList using the add() method.

4. How to check ArrayList contains how many elements.

5. How to use ArrayList in Java.

How to Create an ArrayList and How to add new elements to it ?

This example shows:

• How to create an ArrayList using the ArrayList() constructor.

• Add new elements to an ArrayList using the add() method.

Creating an ArrayList and adding new elements to it Example

/*  Creating an ArrayList and adding new elements to it Example

    Save with file name ArrayListExample.java */

  

import java.util.ArrayList;

  

public class ArrayListExample

{

  public static void main(String args[])

  {

    //java.util.ArrayList DECLARATION

    ArrayList al;

    //java.util.ArrayList OBJECT CREATION

    //USING DEFAULT CONSTRUCTOR

    al = new ArrayList();

    //ADD AN ELEMENT

    al.add("Huda Tutorials");

    al.add("Java Tutorials");

    //DUPLICATES ARE ALLOWED

    al.add("Huda Tutorials");

    al.add("C Tutorials");

    al.add("CPP Tutorials");

    //null ALLOWED

    al.add(null);

    //RETURNS COUNT OF ELEMENTS ArrayList CONTAINS

    System.out.println("Elements Count : " + al.size());

    //java.util.ArrayList OUTPUT

    System.out.println(al);

  }

}

How to use ArrayList with Iterator ?

The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast.

This method do not accept any parameter. The ArrayList.iterator() method returns an Iterator over the elements in this list in proper sequence. If you want to use Iterator follow the following steps

• Obtain an iterator to the start of the collection by calling the collection's iterator() method.

• Set up a loop that makes a call to Iterator.hasNext(). Have the loop iterate as long as Iterator.hasNext() returns true.

• Within the loop, obtain each element by calling next().

The following example shows how to use ArrayList with Iterator.

How to use ArrayList with Iterator

/*  How to use ArrayList with Iterator Example

    Save with file name ArrayListExample2.java  */

  

import java.util.ArrayList;

import java.util.Iterator;

  

public class ArrayListExample2

{

  public static void main(String args[])

  {

    //java.util.ArrayList DECLARATION

    ArrayList al;

    //java.util.ArrayList OBJECT CREATION

    //USING DEFAULT CONSTRUCTOR

    al = new ArrayList();

    //ADD AN ELEMENT

    al.add("Huda Tutorials");

    al.add("Java Tutorials");

    //DUPLICATES ARE ALLOWED

    al.add("Huda Tutorials");

    al.add("C Tutorials");

    al.add("CPP Tutorials");

    //null ALLOWED

    al.add(null);

    //RETURNS COUNT OF ELEMENTS ArrayList CONTAINS

    System.out.println("Elements Count : " + al.size());

    //java.util.ArrayList OUTPUT

    Iterator itr = al.iterator();

    while(itr.hasNext())

    {

      System.out.println(itr.next());

    }

  }

}

How to Create an ArrayList from another Collection ?

An ArrayList can be created from another collection using the java.util.Arrays.asList() method. The following program demonstrates :

• How to create an ArrayList from another collection using the ArrayList(Collection c) constructor.

• How to add all the elements from an existing collection to the new ArrayList using the addAll() method.

How to Create an ArrayList from another Collection Example

/*  How to Create an ArrayList from another Collection Example

    Save with file name CreateArrayListFromCollectionExample.java   */

  

import java.util.ArrayList;

import java.util.List;

  

public class CreateArrayListFromCollectionExample

{

  

    public static void main(String[] args)

    {

      List anotherCollection = new ArrayList();

      anotherCollection.add(12);

      anotherCollection.add(13);

      anotherCollection.add(15);

      // Creating an ArrayList from another collection

      List firstArrayList = new ArrayList(anotherCollection);

      List anotherArrayList = new ArrayList();

      anotherArrayList.add(23);

      anotherArrayList.add(27);

      anotherArrayList.add(29);

      // Adding an entire collection to an ArrayList

      firstArrayList.addAll(anotherArrayList);

      System.out.println(firstArrayList);

    }

}

How to check if an ArrayList is empty ?

You can check if an ArrayList is empty using the ArrayList.isEmpty() method.

How to find the size of an ArrayList ?

You can find the size of an ArrayList using the ArrayList.size() method.

How to access the element at a particular index in an ArrayList ?

You can access the element at a particular index in an ArrayList using the ArrayList.get() method.

How to modify the element at a particular index in an ArrayList ?

You can modify the element at a particular index in an ArrayList using the ArrayList.set() method.

The following example shows how to use ArrayList with Arrays, List and Iterator.

java.util.ArrayList class Example 3

/*  Java ArrayList class Example 3

    Save with file name ArrayListExample3.java  */

  

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;

  

public class ArrayListExample3

{

  public static void main(String args[])

  {

    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

    List s; //java.util.List DECLARATION

    //java.util.List OBJECT CREATION USING ARRAY AS LIST

    s = new ArrayList(Arrays.asList(elements));

    //java.util.List OUTPUT

    Iterator itr = s.iterator();

    while(itr.hasNext())

    {

      System.out.println(itr.next());

    }

  }

}

java.util.ArrayList class Example 4

/*  Java ArrayList class Example 4

    Save with file name ArrayListExample4.java  */

  

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;

  

public class ArrayListExample4

{

  public static void main(String args[])

  {

    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

    List s; //java.util.List DECLARATION

    //java.util.List OBJECT CREATION USING ARRAY AS LIST

    s = new ArrayList(Arrays.asList(elements));

    //ADD ELEMENT TO List COLLECTION

    s.add("NetBeans Tutorials");

    //DISPLAY SIZE OF THE List COLLECTION

    System.out.println("List Collection Size : "+s.size());

    //CHECK THE List COLLECTION IS EMPTY

    System.out.println("List Collection is Empty : "+s.isEmpty());

    //CHECK THE GIVEN ELEMENT IN List COLLECTION

    System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials"));

    //java.util.List OUTPUT

    System.out.println();

    System.out.println("Elements Before Element Remove");

    Iterator itr = s.iterator();

    while(itr.hasNext())

    {

      System.out.println(itr.next());

    }

    s.remove("C Tutorials");

    System.out.println();

    System.out.println("Elements After Element Remove");

    itr = s.iterator();

    while(itr.hasNext())

    {

      System.out.println(itr.next());

    }

  }

}

Removing elements from an ArrayList

How to remove the element at a given index in an ArrayList ?

You can remove the element at a given index in an ArrayList using ArrayList.remove(int index) method.

How to remove an element from an ArrayList ?

You can remove matched element from an ArrayList using ArrayList.remove(Object o) method.

How to remove all the elements from an ArrayList ?

You can remove all the elements from an ArrayList using ArrayList.removeAll() method.

How to remove all the elements matching a given predicate from an ArrayList ?

You can remove all the elements matching a given predicate from an ArrayList using ArrayList.removeIf() method.

How to clear an ArrayList ?

You can clear an ArrayList using ArrayList.clear() method.

The following example shows how to compare two List Collections.

How to compare two List Collections

/*  How to compare two List Collections Example

    Save with file name ArrayListExample5.java  */

  

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;

  

public class ArrayListExample5

{

  public static void main(String args[])

  {

    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

    String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};

    //java.util.List DECLARATION

    List s, s2;

    //java.util.List OBJECT CREATION USING ARRAY AS LIST

    s = new ArrayList(Arrays.asList(elements));

    s2 = new ArrayList(Arrays.asList(elements2));

    //COMPARE TWO COLLECTIONS

    System.out.println("Equals : " + s2.equals(s));

    //CONTAINS COLLECTION IN OTHER COLLECTION

    System.out.println("Contains : " + s2.containsAll(s));

  }

}

The following example shows how to save List Collection into file.

How to save List Collection into file

/*  how to save List Collection into file Example

    Save with file name ArrayListExample6.java  */

  

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;

  

public class ArrayListExample6

{

  public static void main(String args[])

  {

    try

    {

      String elements[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};

      //java.util.ArrayList DECLARATION

      List s;

      //java.util.List OBJECT CREATION USING ARRAY AS LIST

      s = new ArrayList(Arrays.asList(elements));

      //FileOutputStream CREATION

      FileOutputStream fos = new FileOutputStream("List.set");

      //ObjectOutputStream CREATION

      ObjectOutputStream oos = new ObjectOutputStream(fos);

      //WRITE List OBJECT TO ObjectOutputStream

      oos.writeObject(s);

      //CLOSE THE ObjectOutputStream

      oos.close();

      System.out.println("List Collection Saved into File Sucessfully");

    }

    catch(Exception e)

    {

      System.out.println("Error Occurred : " + e.getMessage());

    }

  }

}

The following example shows how to retrieve List Collection from file.

How to retrieve List Collection from file

/*  How to retrieve List Collection from file Example

    Save with file name ArrayListExample7.java  */

  

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

  

public class ArrayListExample7

{

  public static void main(String args[])

  {

    try

    {

      //java.util.ArrayList DECLARATION

      List s;

      //FileInputStream CREATION

      FileInputStream fis = new FileInputStream("List.set");

      //ObjectInputStream CREATION

      ObjectInputStream ois = new ObjectInputStream(fis);

      //READ List OBJECT FROM ObjectInputStream

      s = (List) ois.readObject();

      ois.close();

      System.out.println(s);

    }

    catch(Exception e)

    {

      System.out.println("Error Occurred : " + e.getMessage());

    }

  }

}

The following example shows how to use ArrayList with Arrays, List and ListIterator.

How to use ArrayList with Arrays

/*  how to use ArrayList with Arrays Example

    Save with file name ArrayListExample8.java  */

  

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.ListIterator;

  

public class ArrayListExample8

{

  public static void main(String args[])

  {

    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

    List s; //java.util.List DECLARATION

    //java.util.List OBJECT CREATION USING ARRAY AS LIST

    s = new ArrayList(Arrays.asList(elements));

    //java.util.List OUTPUT

    ListIterator itr = s.listIterator();

    while(itr.hasNext())

    {

      System.out.println(itr.next());

    }

    System.out.println("----- Reverse Order -----");

    //java.util.List OUTPUT IN REVERSE ORDER

    ListIterator itr2 = s.listIterator(s.size());

    while(itr2.hasPrevious())

    {

      System.out.println(itr2.previous());

    }

  }

}

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download