Tuesday, 27 June 2017

ArrayList and It's Methods

ArrayList:

ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null.

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.



Following is the list of the constructors provided by the ArrayList class.
ArrayList( ) - Default constructor:

This constructor builds an empty array list.

Consider following example where we create an empty ArrayList with it's default constructor.

import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<Integer> elements = new ArrayList<>();
    System.out.println(elements.size());
  }
}

Output:
0

ArrayList(Collection c):

This constructor builds an array list that is initialized with the elements of the collection c.

Consider you have a Set collection and you want to covert from Set to an ArrayList. This constructor comes handy for these operations, like, converting any other collection to ArrayList or creating a replica of existing ArrayList.

Example for converting as Set to an ArrayList:


import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final Set<Integer> set = new HashSet<>();
    set.add(1);
    set.add(2);
    set.add(3);
    //Converting Set to arraylist
    final ArrayList<Integer> arrayList = new ArrayList<>(set);
    System.out.println(arrayList);

    //Creating replica of existing arraylist
    final ArrayList<Integer> arrayList2 = new ArrayList<>(arrayList);
    System.out.println(arrayList2);
  }
}

Output:
[1, 2, 3]
[1, 2, 3]


ArrayList(int capacity):

This 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.

Suppose you already have an Array with the size 5 and you decided to convert Array to ArrayList. You can create Arraylist with exactly the size of the Array which you want to convert.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final Integer[] intArray = {1, 2, 3, 4, 5};
    //Converting Array to ArrayList
    final ArrayList<Integer> arrayList = new ArrayList<>(5);
    System.out.println(arrayList.size);
  }
}

Output:
5

Note: Arrays.asList() converts any array to List which is from Arrays class. We will discuss more about Arrays class later in this tutorial.

Now you know how to create an ArrayList. ArrayList class so many predefinaed methods which helps to finish out task super easy.  We will discuss some important methods.

Note: For Java best practices in creating a Linked List please follow post Programming to Interfaces.


Add Method:

There are 2 add methods available in ArrayList.

They are,

boolean add(Object o): appends an element to the end of an ArrayList.

void add(int index, Object element): Inserts the specified element at the specified position index in this list. When you insert an element at any index, then it shifts the following elements to make room. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).

Example below shows how to use effectively above add methods:

import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    // Create an ArrayList and add two strings.
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    System.out.println(list);

    // Add an extra element at index 0.
    // This will move all the existing following elements to make room.
    list.add(0, "Benz");
    System.out.println(list);
  }
}

Output:
[Audi, BMW]
[Benz, Audi, BMW]


addAll Method:
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.



import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");
    System.out.println("Original ArrayList: " + list);
    // Let's create a duplicate ArrayList of above using addAll method
    final ArrayList<String> duplicate = new ArrayList<>();
    duplicate.addAll(list);
    System.out.println("Duplicate ArrayList: " + duplicate);
  }
}

Ouput:
Original ArrayList: [Audi, BMW, Benz]
Duplicate ArrayList: [Audi, BMW, Benz]

set Method:
Replaces the element at the specified position with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).

import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    System.out.println("ArrayList before Set operation: " + list);
    //Replace 0th element which is Audi with Honda
    list.set(0, "Honda");
    System.out.println("ArrayList After Set operation: " + list);
  }
}

Ouput:
ArrayList before Set operation: [Audi, BMW, Benz]
ArrayList After Set operation: [Honda, BMW, Benz]


Get Method:

Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).



import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    // Get 2nd element which is BMW. We have to use index 1 as list index starts from 0.
    System.out.println("2nd Element of the ArrayList: " + list.get(1));
  }
}

Output:
BMW



size Method:

Returns the number of elements in this list.



import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    // print the current size of the ArrayList
    System.out.println("The size of the ArrayList: " + list.size());

  }
}

Output:
The size of the ArrayList: 3



contains Method:

Searches whether a given element is present in the existing list.


import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    System.out.println("Is list contains Audi: " + list.contains("Audi"));  
  }
}

Output:
The size of the LinkedList: 3
Is list contains Audi: true


clear Method:

Removes all of the elements from this list. i.e. resets the list and size to 0.


isEmpty Method:

Check whether a list is empty means no elements in it. Returns true if empty or else false.

Let's use both clear and isEmpty methods in below example:

import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    // print the current size of the ArrayList
    System.out.println("The size of the ArrayList: " + list.size());
    // Reset the list using clear method
    list.clear();
    System.out.println("Is ArrayList empty: " + list.isEmpty());  
  }
}

Output:
The size of the ArrayList: 3
Is ArrayList empty: true


remove Method:

Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).

import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    // print the current size of the ArrayList
    System.out.println("ArrayList before removing BMW which is 2nd element: " + list);

    // Removing BMW which is 2nd element. We have to use index 1 to for 2nd element as list index
    // starts from 0;
    list.remove(1);
    System.out.println("ArrayList after removing BMW which is 2nd element: " + list);
  }
}

Output:
ArrayList before removing BMW which is 2nd element: [Audi, BMW, Benz]
ArrayList after removing BMW which is 2nd element: [Audi, Benz]


indexOf Method:

Returns the index in of the first occurrence of the specified element, or -1 if the List does not contain this element.



import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    // print the current size of the ArrayList
    System.out.println("Printing index of BWM: " + list.indexOf("BMW"));
  }
}


Output:
Printing index of BWM: 1


toArray Method:

Returns an array containing all of the elements in it's list in the correct order. Throws NullPointerException if the specified array is null.



import java.util.ArrayList;

public class ArrayListDemo {

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    // Converting ArrayList to an Array
    Object[] array = list.toArray();
  }
}

ArrayList as a Method Arguement: 

An ArrayList can be passed as an argument to another method like in below example.

import java.util.ArrayList;

public class ArrayListDemo {

  public static void printArrayList(final ArrayList<String> arrayList) {
    for (final String item : arrayList) {
      System.out.println(item);
    }
  }

  public static void main(final String[] args) {
    final ArrayList<String> list = new ArrayList<>();
    list.add("Audi");
    list.add("BMW");
    list.add("Benz");

    printArrayList(list);
  }
}

Output:
Audi
BMW
Benz

Here:I have a method to print ArrayList values that receives an ArrayList as an argument. This method does not create new ArrayList objects. So, this method can be reused whenever you want to print the values of an ArrayList. Thus you are reducing the redundant code.

No comments:

Post a Comment