$show=/label

Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers

SHARE:

A complete guide to ArrayList in java with examples and commonly asked interview questions with answers. ArrayList Cookbook and recipes.

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.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers
Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers
A complete guide to ArrayList in java with examples and commonly asked interview questions with answers. ArrayList Cookbook and recipes.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgy2kOpFT9KJEzvOzzN7n6CiZz0gDfcH2Bf0usa90VM9FjfJaIqiPxF1dEEYokmPUSzOgGSMqwgJyLWyiaktRot7tbO7nBfxGVlBwbboiLJPKgQQXxAQbidWrUi_v8NFRBfaqzJERjbBzw/s640/Java+ArrayList+Examples+Collection+API+ArrayList+Interview+Questions+and+Answers.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgy2kOpFT9KJEzvOzzN7n6CiZz0gDfcH2Bf0usa90VM9FjfJaIqiPxF1dEEYokmPUSzOgGSMqwgJyLWyiaktRot7tbO7nBfxGVlBwbboiLJPKgQQXxAQbidWrUi_v8NFRBfaqzJERjbBzw/s72-c/Java+ArrayList+Examples+Collection+API+ArrayList+Interview+Questions+and+Answers.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/03/java-arraylist-examples-collection-api-interview-questions.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/03/java-arraylist-examples-collection-api-interview-questions.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content