Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, March 25, 2020

Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers

1. Introduction


In this tutorial, We'll be learning today's java collection API ArrayList class and its methods with examples. And also understand how ArrayList will be asked in the interview and how to solve the problems with ArrayList. Refer to Java 13 API Ref.


Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers




2. Java ArrayList


ArrayList is part of java.util package and it implements List interface. ArrayList underlying data structure is Arrays. Nowadays ArrayList is used as an alternative to the Arrays because there are lots of drawbacks when working with arrays. Mainly resizing the array when it reaches its size or adding elements in the middle of the array.

The main advantage of ArrayList is resizable implemented based on the List interface and can add any type of data including null values.

It stores the values in order and value can be sorted using Collections.sort() method.

Let us create an object to ArrayList using the new keyword.

ArrayList<String> list = new ArrayList<>();

3. ArrayList Methods


ArrayList comes with the most commonly used features such as adding, removing, getting the values from a position of the list, adding a value a given index, checking the value is present in the list and getting the size of the ArrayList with an exact count that has been added values.

ArrayList real time examples

3.1 public boolean add(E e)


Adds a new value at the end of the list.

list.add("java");

This statement adds the value in the last position to the ArrayList.

3.2 public void add(int index, E element)


Adds the value at the given index.

list.add(5, "programto");

List indexes start from 0. So, String "programto" will be added at index 6. If the a value already exists at index 6 then first all values from index 6 will be shifted to the right by one index till the last element. After shifting, the new element will be added at index 6.

Let us take another example with the add(index) method.

list.add("one");
list.add("Two");
list.add("Three");

System.out.println("list values : " + list);

list.add(1, "Four");

System.out.println("List values after adding value at index 1 : " + list);

Output:

list values : [one, Two, Three]
List values after adding value at index 1 : [one, Four, Two, Three]

Value at index 1 is shifted to right till last value and added new value at index 1.

3.3  public boolean remove(Object o)


Removes the values from a list and returns true if removed otherwise false. Read more

boolean removed = list.remove("four");
System.out.println("removed value foour " + removed);

This returns false because 'four' is not found in the list because stored data in the list is case sensitive. So need to pass list.remove("Four") then it finds the match and returns true.

If the list has the same value multiple time then it removes the first occurrence of the value.

list.add("Duplicate");
list.add("Duplicate");
list.add("Duplicate");

Added "Duplicate" string three times and now call remove("Duplicate") method.

list.add("Duplicate");
list.add("Duplicate");
list.add("Duplicate");
list.add("Unique");

System.out.println("list : " + list);

list.remove("Duplicate");

System.out.println("List after remove : " + list);

Output:

list : [one, Two, Three, Duplicate, Duplicate, Duplicate, Unique]
List after remove : [one, Two, Three, Duplicate, Duplicate, Unique]

3.4 public E remove(int index)


Removes the value from the index and returns the deleted value.

String deletedValue = list.remove(5);
System.out.println("Removed value at index 5 : "+deletedValue);

This prints below

Removed value at index 5 : Unique

When a value is removed from an index then all values will be shifted to left.

If the index not in the list range then it will throw IndexOutOfBoundsException.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 16 out of bounds for length 6
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.remove(ArrayList.java:535)
    at com.java.w3schools.blog.arraylist.ArrayListMethodsExamples.main(ArrayListMethodsExamples.java:39)

3.5 public int size()


Returns the count of the values stored in the list. This method is used to find the length of list.

int size = list.size();
System.out.println("size : " + size);


It returns 5 because it stored 5 string values.

ArrayList internally maintains a private int instance variable that will be increased by 1 when a new value added and size will downsized by 1 if remove method is invoked.

3.6 public E set(int index, E element)


set() method useful when don't want to shift all values and just update the value at a index.

System.out.println("list.get(2) : "+list.get(2));
list.set(2, "New Value");
System.out.println("list.get(2) value after update  : "+list.get(2));

This code will update the value to "New Value" at index 2.

3.7  public boolean addAll(Collection<? extends E> c)


Add the list values to the current list.

List anotehrList = new ArrayList<>();
anotehrList.add("1");
anotehrList.add("one");

list.addAll(anotehrList);

System.out.println("list : " + list);
        
Output:

list : [one, Two, New Value, Duplicate, Duplicate, 1, One]

addAll() method returns true if the current list not added with new values.

3.8 public boolean removeAll(Collection<?> c)


Remove the given list of values from the current list. If the values are not present in the list then no action will be done.

list.removeAll(anotehrList);

3.9 Full Example:


package com.java.w3schools.blog.arraylist;

import java.util.ArrayList;
import java.util.List;

/**
 * Java ArrayList methods examples
 * 
 * @version javaprogramto.com
 */
public class ArrayListMethodsExamples {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();

        list.add("one");
        list.add("Two");
        list.add("Three");

        System.out.println("list values : " + list);

        list.add(1, "Four");

        System.out.println("List values after adding value at index 1 : " + list);

        boolean removed = list.remove("Four");
        System.out.println("removed value foour " + removed);

        list.add("Duplicate");
        list.add("Duplicate");
        list.add("Duplicate");
        list.add("Unique");

        System.out.println("list : " + list);

        list.remove("Duplicate");

        System.out.println("List after remove : " + list);

        String deletedValue = list.remove(5);
        System.out.println("Removed value at index 5 : " + deletedValue);

        int size = list.size();
        System.out.println("size : " + size);

        System.out.println("list.get(2) : " + list.get(2));
        list.set(2, "New Value");
        System.out.println("list.get(2) value after update  : " + list.get(2));

        List anotehrList = new ArrayList<>();
        anotehrList.add("1");
        anotehrList.add("one");

        //list.addAll(anotehrList);

        System.out.println("list : " + list);

        list.removeAll(anotehrList);
        System.out.println("list : " + list);

        List<String> way1 = new ArrayList<>();

        List<String> way2 = new ArrayList<>(100);

        List<String> way3 = new ArrayList<>(anotehrList);

        way1.add("welcome");
        way1.add("to");
        way1.add("javaprogramto.com");
        
        boolean found = way1.contains("javaprogramto.com");
        System.out.println("found : "+found);
        
        int index = way1.indexOf("javaprogramto.com");
        System.out.println("index : "+index);
        

    }

}

4. ArrayList Interview Questions


We'll see the most frequently asked interview questions.

4.1 Why ArrayList is considered over Array?


Answer: 
Array is having fixed size hence can not be extended once it is full. Whereas ArrayList size can be grown dynamically at run time and we no need to handle explicitly increasing the size. If there is any value removed from it then we can not reutilize the space from the removed index (shifting values to left side not done).

ArrayList internally having many capabilities and makes our life easy.

4.2 How many ways ArrayList object can be created?


Answer: 

Arraylist can be created in many ways as below using the overloaded constructor.
With default size 10 : List<String> way1 = new ArrayList<>();
With a specific size : List<String> way2 = new ArrayList<>(100);
From an existing Collection with constructor : List<String> way3 = new ArrayList<>(anotehrList);

4.3 Can we update the value of a specific index in ArrayList?


Answer: Yes. Value can be updated at a given index using set(index, value) method.

4.4 How to find a value present or not in the ArrayList or List?


Answer:The list has two methods to check whether a value is in the list or not.

public int indexOf​(Object o):

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


public boolean contains​(Object o):

Returns true if this list contains the specified element.

way1.add("welcome");
way1.add("to");
way1.add("javaprogramto.com");

boolean found = way1.contains("javaprogramto.com");
System.out.println("found : "+found);

int index = way1.indexOf("javaprogramto.com");
System.out.println("index : "+index);

Output:

found : true
index : 2

4.5 Is ArrayList synchronized and safe to use by multiple threads?


Answer: 
Generally, Most of the applications in the finance domain are concurrent based and multiple threads will be accessing the same ArrayList object. In that case, multiple threads will try to add or modify and remove the data and will be seeing the data inconsistent. So, you can say confidently it is not thread-safe by default. Read the next question on how to thread-safe ArrayList.

4.6 How to prove ArrayList is not threaded safe with a test?


Answer: 

An example program to see the size of the araylist is inconsistent that cause to throw runtime exception.

package com.java.w3schools.blog.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListNonThreadSafeExample {

    public static void main(String[] args) throws InterruptedException {
        List a = new ArrayList(1);
        Thread t1 = new Thread() {
            public void run() {
                while (true) {
                    a.add("du");
                }
            }
        };

        Thread t2 = new Thread() {
            public void run() {
                while (true) {
                    a.add("String");
                }
            }
        };

        t2.start();
        t1.start();

    }

}

Output:

Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: Index 513847 out of bounds for length 466609
    at java.base/java.util.ArrayList.add(ArrayList.java:486)
    at java.base/java.util.ArrayList.add(ArrayList.java:498)
    at com.java.w3schools.blog.arraylist.ArrayListNonThreadSafeExample$1.run(ArrayListNonThreadSafeExample.java:13)

Read more


4.7 How to make an ArrayList synchronized?


To get synchronized ArrayList, we need to use the utility method synchronizedList() from Collections class.
Collections.synchronized() method internally creates a synchronized list with SynchronizedList class.

Internal code:

static <T> List<T> synchronizedList(List<T> list, Object mutex) {
    return (list instanceof RandomAccess ?
            new SynchronizedRandomAccessList<>(list, mutex) :
            new SynchronizedList<>(list, mutex));
}

Example:

List<String> names = new ArrayList<>();
names.add("chait");
names.add("nag");
names.add("rammy");

// converting list to synchronizedList.
names = Collections.synchronizedList(names);

names.add("brain");
names.add("lara");

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    System.out.println("name : " + it.next());
}    

4.8 how to make ArrayList read-only?


Answer: 
Read-only view means unmodifiable view of the collection. Once values are added to the list and convert the list into unmodifiable using Collections.unmodifiableList(). Now on newly created list, we can not perform add(), remove(), set(), addAll() methods. If you try to do then will get an exception saying java.lang.UnsupportedOperationException.

List<String> namesUnmodifiableList = Collections.unmodifiableList(names);  

4.9 Sorting List


Sorting the ArrayList elements can be done by calling the Collections.sort() method which internally sorts the values in the same list.
Read More

Collections.sort(names);
System.out.println(names);

Output:

[brain, chait, lara, nag, rammy]

5. Conclusion


In this artilce, We've seen ArrayList methods with examples and Interview Questions.

No comments:

Post a Comment

Please do not add any spam links in the comments section.