Saturday, May 19, 2018

ArrayList Class in Java Example

Leave a Comment

ArrayList Class in Java Example

The Array List class extends Abstract List and implements the List interface. Array List supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you may not know util run time precisely how large of an array you need. To handle this situation, the collections framework defines Array List.

In essence, an Array List is a variable-length array of object references. That is, an Array List can dynamically increase or decrease in size. 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.

It is dynamically growing array that stores objects. It is not Synchronized and Vector is a Synchronized

Note: You can’t store primitive data type. we can store only object into Array List.
Array List has the constructors shown here:

Array List Class in Java Example

ArrayList();  //This constructor builds an empty array list
ArrayList(Collection c)  // This constructor builds an array list that is initialized with the elements of collection c.
ArrayList(int capacity)  //This Contructor builds an array list that has the specified initial capacity.

To Create  an Array List

ArrayList arl=new ArrayList();  //creating an object

ArrayList Arl=new ArrayList(20);  //creating an object with the size

To add objects use add() method



To Remove objects use remove()

arl.remove("APPLE");  //remove an string

arl.remove(2);  //removing the string  of specified location

To Know Number of objects, use size()

int n= arl.size()   // It displays the size of the array list.

Example of using an Array List

import java.util.*;

class Arraylist Demo {
 public static void main(String args[]) {

  ArrayList list = new ArrayList(); //creating an object for ArrayList class
  System.out.println("Initial size of al: "+al.size());

  //add  elements to the array list
  al.add(1, "A2″);

  System.out.println("Size of al after additions: +al.size());

  //display the array list
  System.out.println("Content of al: "+al);

  //Remove elements from the array list

  System.out.println("size of al after deletion: "+al.size());
  System.out.println("contents of al: "+al);
If You Enjoyed This, Take 5 Seconds To Share It


Post a Comment