Core Java

OCA Java 8 Preparation : ArrayList

Java Collection framework provides an ArrayList class in package java.util which is used to hold a collection of objects. It implements the List interface(List extends Collection interface).The benefit of using ArrayList over Array is that you do not need to know the size of ArrayList<E> while creating it. It could be thought of as a dynamic array. Rather, its internal implementation makes use of an array to hold its elements.

ArrayList support generics to help you with type-safety. It maintains the insertion order of its elements.

Constructing an ArrayList :

An ArrayList can be created using any of the following constructors :

ArrayList() // initialCapacity is 10
ArrayList(int initialCapacity)
ArrayList(Collection<? extends E> c)

For the OCA Java Exam you are expected to identify valid ways of ArrayList creation.

I. ArrayList<String> arrList = new ArrayList<String>();
  //use of diamond operator
II. ArrayList<String> arrList = new ArrayList<>(); 
III. List<String> arrList = new ArrayList<>();
IV. List<String> arrList2 = new ArrayList<>(arrList);
V. List<String> arrList = new ArrayList<>(20);
VI. List<String> arrList = new ArrayList();

For point (VI.) , the compiler will throw an unchecked warning but the compilation still works fine.

Noteworthy points :
  1. If you have declared the type of an ArrayList to be String, even trying to insert an int value to the list will give a compile time error – incompatible types, so watch out for such cases in the exam.
  2. An ArrayList can hold duplicate values.
  3. Try predicting the output below :
    List<Integer> listInt = new ArrayList<>();
    listInt.add(1);
    listInt.add(2);
    List<String> listStr = new ArrayList(listInt); //works fine
    System.out.println(listStr.get(0)); // throws ClassCastException

ArrayList<E> Methods :

Adding Elements : Below are some available methods that can help you add items to an ArrayList.

boolean add(E element)
void add(int index, E element)

boolean addAll(Collection<? extemds E> c)
boolean addAll(int index, Collection<? extends E> c)

add(E element) or addAll(Collection c) methods add the elements to the end of the list.

add(int index, E element) & addAll(int index, Collection c) methods add the given value to the specified index by shifting elements starting from that index towards the end of the list , in order to make sufficient room. If the index is invalid(index < 0 || index >= size()), this method throws IndexOutOfBoundException.

The boolean return type specifies that the method returns true if the insertion succeeds.

Example Usage :

List<String> list = new ArrayList<>();
list.add("Harry");
list.add("Jack");
list.add("James");
list.add(1,"Vit");
//prints [Harry, Vit, Jack, James]
System.out.println(list);

 

Removing Elements : Below set of methods can help us when trying to remove an element from ArrayList.

E remove(int index)
boolean remove(Object element)

boolean removeAll(Collection<?> c)
boolean removeIf(Predicate<? super E> filter)

remove(int index) method removes and returns the element at that index. If index is out of range, it throws IndexOutOfBoundException.

remove(Object obj) methods removes the first matching occurrence of object element in the ArrayList. It returns true if the call was successful.

removeAll() methods removes from an ArrayList – all the elements which matches elements in given collection.

removeIf() method removes from an ArrayList all the elements that satisfy the filtering criteria defined by a lambda expression of type Predicate.We’ll cover about it in detail in an upcoming post.

Both removeAll() & removeIf() returns true if the call was successful.

We have already covered StringBuilder & String in our previous posts . If you have gone through it well, hopefully you’ll be in a position to answer the below question :

import java.util.*;
public class Test{

     public static void main(String []args){
        List<String> list1 = new ArrayList<>();
        list1.add(new String("Harry"));
        list1.add(new String("Jack"));
        list1.remove(new String("Jack"));
        System.out.println(list1); //prints [Harry]


        List<StringBuilder> list2 = new ArrayList<>();
       // StringBuilder jack = new StringBuilder("Jack");
        list2.add(new StringBuilder("Harry"));
        list2.add(new StringBuilder("Jack"));
        StringBuilder jack2 = new StringBuilder("Jack");
        System.out.println(list2.contains(jack2));//false
        System.out.println(list2.indexOf(jack2));//-1
        list2.remove(new StringBuilder("Jack"));

        System.out.println(list2); //prints [Harry, Jack]
        
        List<StringBuilder> list3 = new ArrayList<>();
        StringBuilder jack = new StringBuilder("Jack");
        list3.add(new StringBuilder("Harry"));
        list3.add(jack);
        list3.remove(jack);

        System.out.println(list3); //prints [Harry]
        
        }
}

Unlike String, the StringBuilder class doesn’t overrides equals() method.So,  when you call remove() on list2 , default equals() method from the Object class is executed which only makes a reference comparison so the match fails. In case of list3 we are providing the same reference so the element match succeeds and it gets removed the list.

I know this was real brainstorming session. So, let’s keep it a little lighter moving forward, at least for some time from now. So let’s cover some other methods in ArrayList class.

Miscellaneous Methods :

  1. trimToSize() : trims the capacity of the list to its current size.
    void trimToSize()
  2. clear() : It deletes all the elements of the list.
    void clear()
  3. size(): It returns the size of ArrayList.
    int size()
  4. isEmpty() : returns true if list is empty , false otherwise.
    boolean isEmpty()
  5. get() : This method helps in retrieving an element from the list using its positional index.
    E get(int index)
  6. set() : This method replaces a value at a given index.It returns the previous element at the specified index. For invalid index, IndexOutOfBoundException is thrown.
    E set(int index, E element)
  7. equals() : Compares the specified object with this list for object value equality.
    boolean equals(Object obj)
  8. contains() : Determines whether a given object is contained in the list or not.
    boolean contains(Object element)
  9. indexOf() & lastIndexOf() : Returns the indexes of first and last occurrences of the given element. If no such element exists, it returns -1.
    int indexOf(Object element)
    int lastIndexOf(Object element)
  10.  clone() : This class overrides the clone() method from Object class and creates a shallow copy of the list. “Shallow Copy” means it creates a new instance with its element references copied, but not the objects themselves.

Traversing an ArrayList :

  1. Using a for or forEach loop : Note that while traversing list using a for or forEach loop, in case you try to remove an element from the list, JVM will throw ConcurrentModificationException.
      List<Integer> arrList = new ArrayList<>(); 
     arrList.add(1); 
     arrList.add(2);
     arrList.add(3); 
     arrList.add(4); 
     //using for loop
     for(int i=0; i< arrList.size(); i++){ 
     System.out.println(arrList.get(i));
    arrList.remove(i); //throws ConcurrentModificationException
     } 
     //using forEach loop 
     for(int element : arrList){ 
     System.out.println(element); 
     } 
    

     

  2.  Iterator or ListIterator : Both Iterator & ListIterator belong to java.util package and can be used to traverse through the list. Both of them allows you to remove an element while iterating through the list. ListIterator has some special advantages over Iterator which we can cover briefly. But first, let’s look at a simple implementation of iterating a list using ListIterator.
    ListIterator itr = arrayList.listIterator();
    while(itr.hasNext()){
     System.out.println(itr.next());
    }

    Let’s look at some differences between Iterator and a ListIterator.

    IteratorListIterator
    Methods :
    hasNext()
    next()
    remove()
    Methods :
    add(E e)
    hasNext()
    hasPrevious()
    next()
    nextIndex()
    previous()
    previousIndex()
    remove()
    set(E e)
    Cannot replace the existing elementCan replace the existing element
    Cannot add element to collection while traversing it Can add element to collection while traversing it
    Can traverse in only forward directionCan traverse in both directions

Converting ArrayList to an Array :

It can be achieved using the toArray() method. Note that if you modify the output array say by swapping its elements or so it will not impact the ArrayList. However, if you modify the state of elements of the returned array then the modified state of elements will be reflected in the ArrayList.

Object[] toArray();

Sorting an ArrayList :

Sorting an ArrayList can be achieved using a sort() method available in java.util.Collections class.

Collections.sort(List<E> list)
2 comments

Leave a Comment

Your email address will not be published. Required fields are marked *