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 :

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

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 :

ArrayList<E> Methods :

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

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 :

 

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

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 :

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.
  2. clear() : It deletes all the elements of the list.
  3. size(): It returns the size of ArrayList.
  4. isEmpty() : returns true if list is empty , false otherwise.
  5. get() : This method helps in retrieving an element from the list using its positional 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.
  7. equals() : Compares the specified object with this list for object value equality.
  8. contains() : Determines whether a given object is contained in the list or not.
  9. indexOf() & lastIndexOf() : Returns the indexes of first and last occurrences of the given element. If no such element exists, it returns -1.
  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.

     
  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.

    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.

Sorting an ArrayList :

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

2 comments

Leave a Comment

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