# ArrayList - Examples and practice problems

ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.

ArrayList is part of Java’s collection framework and implements Java’s `List` interface.![Java ArrayList in Collection Hierarchy](https://www.callicoder.com/assets/images/post/large/java-arraylist-hierarchy.jpg)

Following are few key points to note about ArrayList in Java -

* An ArrayList is a re-sizable array, also called a dynamic array. It grows its size to accommodate new elements and shrinks the size when the elements are removed.
* ArrayList internally uses an array to store the elements. Just like arrays, It allows you to retrieve the elements by their index.
* Java ArrayList allows duplicate and null values.
* Java ArrayList is an ordered collection. It maintains the insertion order of the elements.
* You cannot create an ArrayList of primitive types like `int`, `char` etc. You need to use boxed types like `Integer`, `Character`, `Boolean` etc.
* Java ArrayList is not synchronized. If multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. You must explicitly synchronize access to an ArrayList if multiple threads are gonna modify it.

### Creating an ArrayList and adding new elements to it <a href="#creating-an-arraylist-and-adding-new-elements-to-it" id="creating-an-arraylist-and-adding-new-elements-to-it"></a>

This example shows:

* How to create an ArrayList using the [`ArrayList()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--) constructor.
* Add new elements to an ArrayList using the [`add()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-E-) method.

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

public class CreateArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        List<String> animals = new ArrayList<>();

        // Adding new elements to the ArrayList
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals);

        // Adding an element at a particular index in an ArrayList
        animals.add(2, "Elephant");

        System.out.println(animals);

    }
}
```

```
# Output
[Lion, Tiger, Cat, Dog]
[Lion, Tiger, Elephant, Cat, Dog]
```

### Creating an ArrayList from another collection <a href="#creating-an-arraylist-from-another-collection" id="creating-an-arraylist-from-another-collection"></a>

This example shows:

* How to create an ArrayList from another collection using the [`ArrayList(Collection c)`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-)constructor.
* How to add all the elements from an existing collection to the new ArrayList using the [`addAll()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#addAll-java.util.Collection-)method.

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

public class CreateArrayListFromCollectionExample {

    public static void main(String[] args) {
        List<Integer> firstFivePrimeNumbers = new ArrayList<>();
        firstFivePrimeNumbers.add(2);
        firstFivePrimeNumbers.add(3);
        firstFivePrimeNumbers.add(5);
        firstFivePrimeNumbers.add(7);
        firstFivePrimeNumbers.add(11);

        // Creating an ArrayList from another collection
        List<Integer> firstTenPrimeNumbers = new ArrayList<>(firstFivePrimeNumbers);


        List<Integer> nextFivePrimeNumbers = new ArrayList<>();
        nextFivePrimeNumbers.add(13);
        nextFivePrimeNumbers.add(17);
        nextFivePrimeNumbers.add(19);
        nextFivePrimeNumbers.add(23);
        nextFivePrimeNumbers.add(29);

        // Adding an entire collection to an ArrayList
        firstTenPrimeNumbers.addAll(nextFivePrimeNumbers);

        System.out.println(firstTenPrimeNumbers);
    }
}
```

```
# Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
```

### Accessing elements from an ArrayList <a href="#accessing-elements-from-an-arraylist" id="accessing-elements-from-an-arraylist"></a>

This example shows:

* How to check if an ArrayList is empty using the [`isEmpty()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty--) method.
* How to find the size of an ArrayList using the [`size()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#size--) method.
* How to access the element at a particular index in an ArrayList using the [`get()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#get-int-) method.
* How to modify the element at a particular index in an ArrayList using the [`set()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#set-int-E-) method.

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

public class AccessElementsFromArrayListExample {
    public static void main(String[] args) {
        List<String> topCompanies = new ArrayList<>();

        // Check if an ArrayList is empty
        System.out.println("Is the topCompanies list empty? : " + topCompanies.isEmpty());

        topCompanies.add("Google");
        topCompanies.add("Apple");
        topCompanies.add("Microsoft");
        topCompanies.add("Amazon");
        topCompanies.add("Facebook");

        // Find the size of an ArrayList
        System.out.println("Here are the top " + topCompanies.size() + " companies in the world");
        System.out.println(topCompanies);

        // Retrieve the element at a given index
        String bestCompany = topCompanies.get(0);
        String secondBestCompany = topCompanies.get(1);
        String lastCompany = topCompanies.get(topCompanies.size() - 1);

        System.out.println("Best Company: " + bestCompany);
        System.out.println("Second Best Company: " + secondBestCompany);
        System.out.println("Last Company in the list: " + lastCompany);

        // Modify the element at a given index
        topCompanies.set(4, "Walmart");
        System.out.println("Modified top companies list: " + topCompanies);
    }
}
```

```
# Output
Is the topCompanies list empty? : true
Here are the top 5 companies in the world
[Google, Apple, Microsoft, Amazon, Facebook]
Best Company: Google
Second Best Company: Apple
Last Company in the list: Facebook
Modified top companies list: [Google, Apple, Microsoft, Amazon, Walmart]
```

### Removing elements from an ArrayList <a href="#removing-elements-from-an-arraylist" id="removing-elements-from-an-arraylist"></a>

This example shows:

1. How to remove the element at a given index in an ArrayList | [remove(int index)](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-int-)
2. How to remove an element from an ArrayList | [remove(Object o)](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-)
3. How to remove all the elements from an ArrayList that exist in a given collection | [removeAll()](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#removeAll-java.util.Collection-)
4. How to remove all the elements matching a given predicate | [removeIf()](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#removeIf-java.util.function.Predicate-)
5. How to clear an ArrayList | [clear()](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#clear--)

```java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class RemoveElementsFromArrayListExample {
    public static void main(String[] args) {
        List<String> programmingLanguages = new ArrayList<>();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Kotlin");
        programmingLanguages.add("Python");
        programmingLanguages.add("Perl");
        programmingLanguages.add("Ruby");

        System.out.println("Initial List: " + programmingLanguages);

        // Remove the element at index `5`
        programmingLanguages.remove(5);
        System.out.println("After remove(5): " + programmingLanguages);

        // Remove the first occurrence of the given element from the ArrayList
        // (The remove() method returns false if the element does not exist in the ArrayList)
        boolean isRemoved = programmingLanguages.remove("Kotlin");
        System.out.println("After remove(\"Kotlin\"): " + programmingLanguages);

        // Remove all the elements that exist in a given collection
        List<String> scriptingLanguages = new ArrayList<>();
        scriptingLanguages.add("Python");
        scriptingLanguages.add("Ruby");
        scriptingLanguages.add("Perl");

        programmingLanguages.removeAll(scriptingLanguages);
        System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages);

        // Remove all the elements that satisfy the given predicate
        programmingLanguages.removeIf(new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.startsWith("C");
            }
        });

        /*
            The above removeIf() call can also be written using lambda expression like this -
            programmingLanguages.removeIf(s -> s.startsWith("C"))
        */

        System.out.println("After Removing all elements that start with \"C\": " + programmingLanguages);

        // Remove all elements from the ArrayList
        programmingLanguages.clear();
        System.out.println("After clear(): " + programmingLanguages);
    }
}
```

```
# Output
Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby]
After remove(5): [C, C++, Java, Kotlin, Python, Ruby]
After remove("Kotlin"): [C, C++, Java, Python, Ruby]
After removeAll(scriptingLanguages): [C, C++, Java]
After Removing all elements that start with "C": [Java]
After clear(): []
```

### Iterating over an ArrayList <a href="#iterating-over-an-arraylist" id="iterating-over-an-arraylist"></a>

The following example shows how to iterate over an ArrayList using

1. Java 8 [`forEach`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#forEach-java.util.function.Consumer-) and lambda expression.
2. [`iterator()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#iterator--).
3. [`iterator()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#iterator--) and Java 8 [forEachRemaining()](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-) method.
4. [`listIterator()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#listIterator-int-).
5. Simple for-each loop.
6. for loop with index.

```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IterateOverArrayListExample {
    public static void main(String[] args) {
        List<String> tvShows = new ArrayList<>();
        tvShows.add("Breaking Bad");
        tvShows.add("Game Of Thrones");
        tvShows.add("Friends");
        tvShows.add("Prison break");

        System.out.println("=== Iterate using Java 8 forEach and lambda ===");
        tvShows.forEach(tvShow -> {
            System.out.println(tvShow);
        });

        System.out.println("\n=== Iterate using an iterator() ===");
        Iterator<String> tvShowIterator = tvShows.iterator();
        while (tvShowIterator.hasNext()) {
            String tvShow = tvShowIterator.next();
            System.out.println(tvShow);
        }

        System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ===");
        tvShowIterator = tvShows.iterator();
        tvShowIterator.forEachRemaining(tvShow -> {
            System.out.println(tvShow);
        });

        System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ===");
        // Here, we start from the end of the list and traverse backwards.
        ListIterator<String> tvShowListIterator = tvShows.listIterator(tvShows.size());
        while (tvShowListIterator.hasPrevious()) {
            String tvShow = tvShowListIterator.previous();
            System.out.println(tvShow);
        }

        System.out.println("\n=== Iterate using simple for-each loop ===");
        for(String tvShow: tvShows) {
            System.out.println(tvShow);
        }

        System.out.println("\n=== Iterate using for loop with index ===");
        for(int i = 0; i < tvShows.size(); i++) {
            System.out.println(tvShows.get(i));
        }
    }
}
```

```
# Output
=== Iterate using Java 8 forEach and lambda ===
Breaking Bad
Game Of Thrones
Friends
Prison break

=== Iterate using an iterator() ===
Breaking Bad
Game Of Thrones
Friends
Prison break

=== Iterate using an iterator() and Java 8 forEachRemaining() method ===
Breaking Bad
Game Of Thrones
Friends
Prison break

=== Iterate using a listIterator() to traverse in both directions ===
Prison break
Friends
Game Of Thrones
Breaking Bad

=== Iterate using simple for-each loop ===
Breaking Bad
Game Of Thrones
Friends
Prison break

=== Iterate using for loop with index ===
Breaking Bad
Game Of Thrones
Friends
Prison break
```

The `iterator()` and `listIterator()` methods are useful when you need to modify the ArrayList while traversing.

Consider the following example, where we remove elements from the ArrayList using `iterator.remove()` method while traversing through it -

```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListIteratorRemoveExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(13);
        numbers.add(18);
        numbers.add(25);
        numbers.add(40);

        Iterator<Integer> numbersIterator = numbers.iterator();
        while (numbersIterator.hasNext()) {
            Integer num = numbersIterator.next();
            if(num % 2 != 0) {
                numbersIterator.remove();
            }
        }

        System.out.println(numbers);
    }
}
```

```
# Output
[18, 40]
```

### Searching for elements in an ArrayList <a href="#searching-for-elements-in-an-arraylist" id="searching-for-elements-in-an-arraylist"></a>

The example below shows how to:

* Check if an ArrayList contains a given element | [contains()](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#contains-java.lang.Object-)
* Find the index of the first occurrence of an element in an ArrayList | [indexOf()](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-)
* Find the index of the last occurrence of an element in an ArrayList | [lastIndexOf()](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#lastIndexOf-java.lang.Object-)

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

public class SearchElementsInArrayListExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("John");
        names.add("Alice");
        names.add("Bob");
        names.add("Steve");
        names.add("John");
        names.add("Steve");
        names.add("Maria");

        // Check if an ArrayList contains a given element
        System.out.println("Does names array contain \"Bob\"? : " + names.contains("Bob"));

        // Find the index of the first occurrence of an element in an ArrayList
        System.out.println("indexOf \"Steve\": " + names.indexOf("Steve"));
        System.out.println("indexOf \"Mark\": " + names.indexOf("Mark"));

        // Find the index of the last occurrence of an element in an ArrayList
        System.out.println("lastIndexOf \"John\" : " + names.lastIndexOf("John"));
        System.out.println("lastIndexOf \"Bill\" : " + names.lastIndexOf("Bill"));
    }
}
```

```
# Output
Does names array contain "Bob"? : true
indexOf "Steve": 3
indexOf "Mark": -1
lastIndexOf "John" : 4
lastIndexOf "Bill" : -1
```

### ArrayList of user defined objects <a href="#arraylist-of-user-defined-objects" id="arraylist-of-user-defined-objects"></a>

Since ArrayList supports generics, you can create an ArrayList of **any** type. It can be of simple types like `Integer`, `String`, `Double` or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.

In the following example, you’ll learn how to create an ArrayList of user defined objects.

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

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class ArrayListUserDefinedObjectExample {
    public static void main(String[] args) {
        List<User> users = new ArrayList<>();
        users.add(new User("Rajeev", 25));
        users.add(new User("John", 34));
        users.add(new User("Steve", 29));

        users.forEach(user -> {
            System.out.println("Name : " + user.getName() + ", Age : " + user.getAge());
        });
    }
}
```

```
# Output
Name : Rajeev, Age : 25
Name : John, Age : 34
Name : Steve, Age : 29
```

### Sorting an ArrayList <a href="#sorting-an-arraylist" id="sorting-an-arraylist"></a>

Sorting an ArrayList is a very common task that you will encounter in your programs. In this section, I’ll show you how to -

* Sort an ArrayList using [`Collections.sort()`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-) method.
* Sort an ArrayList using [`ArrayList.sort()`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#sort-java.util.Comparator-) method.
* Sort an ArrayList of user defined objects with a custom comparator.

**1. Sort an ArrayList using Collections.sort() method**

```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListCollectionsSortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(13);
        numbers.add(7);
        numbers.add(18);
        numbers.add(5);
        numbers.add(2);

        System.out.println("Before : " + numbers);

        // Sorting an ArrayList using Collections.sort() method
        Collections.sort(numbers);

        System.out.println("After : " + numbers);
    }
}
```

```
# Output
Before : [13, 7, 18, 5, 2]
After : [2, 5, 7, 13, 18]
```

**2. Sort an ArrayList using ArrayList.sort() method**

```java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ArrayListSortExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Lisa");
        names.add("Jennifer");
        names.add("Mark");
        names.add("David");

        System.out.println("Names : " + names);

        // Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.
        names.sort(new Comparator<String>() {
            @Override
            public int compare(String name1, String name2) {
                return name1.compareTo(name2);
            }
        });

        // The above `sort()` method call can also be written simply using lambda expression
        names.sort((name1, name2) -> name1.compareTo(name2));

        // Following is an even more concise solution
        names.sort(Comparator.naturalOrder());

        System.out.println("Sorted Names : " + names);
    }
}
```

```
# Output
Names : [Lisa, Jennifer, Mark, David]
Sorted Names : [David, Jennifer, Lisa, Mark]
```

**3. Sort an ArrayList of Objects using custom Comparator**

```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    private String name;
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class ArrayListObjectSortExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Sachin", 47));
        people.add(new Person("Chris", 34));
        people.add(new Person("Rajeev", 25));
        people.add(new Person("David", 31));

        System.out.println("Person List : " + people);

        // Sort People by their Age
        people.sort((person1, person2) -> {
            return person1.getAge() - person2.getAge();
        });

        // A more concise way of writing the above sorting function
        people.sort(Comparator.comparingInt(Person::getAge));

        System.out.println("Sorted Person List by Age : " + people);

        // You can also sort using Collections.sort() method by passing the custom Comparator
        Collections.sort(people, Comparator.comparing(Person::getName));
        System.out.println("Sorted Person List by Name : " + people);
    }
}
```

```
# Output
Person List : [{name='Sachin', age=47}, {name='Chris', age=34}, {name='Rajeev', age=25}, {name='David', age=31}]
Sorted Person List by Age : [{name='Rajeev', age=25}, {name='David', age=31}, {name='Chris', age=34}, {name='Sachin', age=47}]
Sorted Person List by Name : [{name='Chris', age=34}, {name='David', age=31}, {name='Rajeev', age=25}, {name='Sachin', age=47}]
```

### Synchronizing Access to an ArrayList <a href="#synchronizing-access-to-an-arraylist" id="synchronizing-access-to-an-arraylist"></a>

The ArrayList class is not synchronized. If multiple threads try to modify an ArrayList at the same time then the final result becomes not-deterministic because one thread might override the changes done by another thread.

**Example Demonstrating ArrayList’s unpredictable behavior in multi-threaded environments**

The following example shows what happens when multiple threads try to modify an ArrayList at the same time.

```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class UnsafeArrayListExample {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> unsafeArrayList = new ArrayList<>();
        unsafeArrayList.add(1);
        unsafeArrayList.add(2);
        unsafeArrayList.add(3);

        // Create a thread pool of size 10
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // Create a Runnable task that increments each element of the ArrayList by one
        Runnable task = () -> {
            incrementArrayList(unsafeArrayList);
        };

        // Submit the task to the executor service 100 times.
        // All the tasks will modify the ArrayList concurrently
        for(int i = 0; i < 100; i++) {
            executorService.submit(task);
        }

        executorService.shutdown();
        executorService.awaitTermination(60, TimeUnit.SECONDS);

        System.out.println(unsafeArrayList);
    }

    // Increment all the values in the ArrayList by one
    private static void incrementArrayList(List<Integer> unsafeArrayList) {
        for(int i = 0; i < unsafeArrayList.size(); i++) {
            Integer value = unsafeArrayList.get(i);
            unsafeArrayList.set(i, value + 1);
        }
    }
}
```

The final output of the above program should be equal to `[101, 102, 103]` because we’re incrementing the values in the ArrayList 100 times. But if you run the program, it will produce different output every time it is run -

```
# Output
[96, 96, 98]
```

Try running the above program multiple times and see how it produces different outputs. To learn more about such issues in multi-threaded programs, check out my article on [Java Concurrency Issues and Thread Synchronization](https://www.callicoder.com/java-concurrency-issues-and-thread-synchronization/).

**Example demonstrating how to synchronize concurrent modifications to an ArrayList**

All right! Now let’s see how we can synchronize access to the `ArrayList` in multi-threaded environments.

The following example shows the synchronized version of the previous example. Unlike the previous program, the output of this program is deterministic and will always be the same.

```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SynchronizedArrayListExample {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> safeArrayList = Collections.synchronizedList(new ArrayList<>());
        safeArrayList.add(1);
        safeArrayList.add(2);
        safeArrayList.add(3);

        // Create a thread pool of size 10
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // Create a Runnable task that increments each element of the ArrayList by one
        Runnable task = () -> {
            incrementArrayList(safeArrayList);
        };

        // Submit the task to the executor service 100 times.
        // All the tasks will modify the ArrayList concurrently
        for(int i = 0; i < 100; i++) {
            executorService.submit(task);
        }

        executorService.shutdown();
        executorService.awaitTermination(60, TimeUnit.SECONDS);

        System.out.println(safeArrayList);
    }

    // Increment all the values in the ArrayList by one
    private static void incrementArrayList(List<Integer> safeArrayList) {
        synchronized (safeArrayList) {
            for (int i = 0; i < safeArrayList.size(); i++) {
                Integer value = safeArrayList.get(i);
                safeArrayList.set(i, value + 1);
            }
        }
    }
}
```

```
# Output
[101, 102, 103]
```

The above example uses [`Collections.synchronizedList()`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedList-java.util.List-) method to get a synchronized view of the ArrayList.

Moreover, the modifications to the ArrayList inside the `incrementArrayList()` method is wrapped inside a `synchronized` block. This ensures that no two threads can increment ArrayList elements at the same time.

_You can also use a_ [_`CopyOnWriteArrayList`_](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) _if you need thread safety. It is a thread-safe version of the ArrayList class. It implements all the mutating operations by making a fresh copy of the ArrayList._

## More Examples :

#### Example a: Add an element to specified index of Java ArrayList Example

```java
/*
  Add an element to specified index of Java ArrayList Example
  This Java Example shows how to add an element at specified index of java
  ArrayList object using add method.
*/
 
import java.util.ArrayList;
 
public class AddElementToSpecifiedIndexArrayListExample {
 
  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
   
    /*
      To add an element at the specified index of ArrayList use
      void add(int index, Object obj) method.
      This method inserts the specified element at the specified index in the
      ArrayList.  
    */
    arrayList.add(1,"INSERTED ELEMENT");
   
    /*
      Please note that add method DOES NOT overwrites the element previously
      at the specified index in the list. It shifts the elements to right side
      and increasing the list size by 1.
    */
 
    System.out.println("ArrayList contains...");
    //display elements of ArrayList
    for(int index=0; index < arrayList.size(); index++)
      System.out.println(arrayList.get(index));
   
  }
}
 
/*
Output would be
ArrayList contains...
1
INSERTED ELEMENT
2
3
*/

```

#### Example b: Get Size of Java ArrayList and loop through elements Example

```java
/*
  Get Size of Java ArrayList and loop through elements Example
  This Java Example shows how to get size or number of elements currently
  stored in ArrayList. It also shows how to loop through element of it.
*/
 
import java.util.ArrayList;
 
public class GetSizeOfArrayListExample {
 
  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist using
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
 
    //To get size of Java ArrayList use int size() method
    int totalElements = arrayList.size();
   
    System.out.println("ArrayList contains...");
    //loop through it
    for(int index=0; index < totalElements; index++)
      System.out.println(arrayList.get(index));
   
  }
}
 
/*
Output would be
ArrayList contains...
1
2
3
*/
```

#### Example c: Search an element of Java ArrayList Example

```java
/*
  Search an element of Java ArrayList Example
  This Java Example shows how to search an element of java
  ArrayList object using contains, indexOf and lastIndexOf methods.
*/
 
import java.util.ArrayList;
 
public class SearchAnElementInArrayListExample {
 
  public static void main(String[] args) {
   
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    arrayList.add("1");
    arrayList.add("2");
 
    /*
      To check whether the specified element exists in Java ArrayList use
      boolean contains(Object element) method.
      It returns true if the ArrayList contains the specified objct, false
      otherwise.
    */
   
    boolean blnFound = arrayList.contains("2");
    System.out.println("Does arrayList contain 2 ? " + blnFound);
 
    /*
      To get an index of specified element in ArrayList use
      int indexOf(Object element) method.
      This method returns the index of the specified element in ArrayList.
      It returns -1 if not found.
    */
 
    int index = arrayList.indexOf("4");
    if(index == -1)
      System.out.println("ArrayList does not contain 4");
    else
      System.out.println("ArrayList contains 4 at index :" + index);
     
    /*
      To get last index of specified element in ArrayList use
      int lastIndexOf(Object element) method.
      This method returns index of the last occurrence of the
      specified element in ArrayList. It returns -1 if not found.
    */
 
    int lastIndex = arrayList.lastIndexOf("1");
    if(lastIndex == -1)
      System.out.println("ArrayList does not contain 1");
    else
      System.out.println("Last occurrence of 1 in ArrayList is at index :" 
                                                              + lastIndex);
     
  }   
}
/*
Output would be
Does arrayList contain 2 ? true
ArrayList contains 4 at index :3
Last occurrence of 1 in ArrayList is at index :5
*/
```

#### Example d: Get Sub List of Java ArrayList Example

```java
*
  Get Sub List of Java ArrayList Example
  This Java Example shows how to get sub list of java ArrayList using subList
  method by providing start and end index.
*/
 
import java.util.ArrayList;
import java.util.List;
 
public class GetSubListOfJavaArrayListExample {
 
  public static void main(String[] args) {
 
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
   
    /*
       To get a sub list of Java ArrayList use
       List subList(int startIndex, int endIndex) method.
       This method returns an object of type List containing elements from
       startIndex to endIndex - 1.
    */
   
    List lst = arrayList.subList(1,3);
       
    //display elements of sub list.
    System.out.println("Sub list contains : ");
    for(int i=0; i< lst.size() ; i++)
      System.out.println(lst.get(i));
     
    /*
      Sub List returned by subList method is backed by original Arraylist. So any
      changes made to sub list will also be REFLECTED in the original Arraylist.
    */
    //remove one element from sub list
    Object obj = lst.remove(0);
    System.out.println(obj + " is removed from sub list");
   
    //print original ArrayList
    System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
    for(int i=0; i< arrayList.size() ; i++)
      System.out.println(arrayList.get(i));
   
  }
 
}
/*
Output would be
Sub list contains :
2
3
2 is removed from sub list
After removing 2 from sub list original ArrayList contains :
1
3
4
5
*/
```

#### Example e: Remove an element from specified index of Java ArrayList&#x20;

```java
/*
  Remove an element from specified index of Java ArrayList Example
  This Java Example shows how to remove an element at specified index of java
  ArrayList object using remove method.
*/
 
import java.util.ArrayList;
 
public class RemoveElementFromArrayListExample {
 
  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
   
    /*
      To remove an element from the specified index of ArrayList use
      Object remove(int index) method.
      It returns the element that was removed from the ArrayList.
    */
    Object obj = arrayList.remove(1);
    System.out.println(obj + " is removed from ArrayList");
   
    System.out.println("ArrayList contains...");
    //display elements of ArrayList
    for(int index=0; index < arrayList.size(); index++)
      System.out.println(arrayList.get(index));
   
  }
}
 
/*
Output would be
2 is removed from ArrayList
ArrayList contains...
1
3
*/
```

#### Example f: Sort elements of Java ArrayList

```java
/*
  Sort elements of Java ArrayList Example
  This Java Example shows how to sort the elements of java ArrayList object using
  Collections.sort method.
*/
 
import java.util.ArrayList;
import java.util.Collections;
 
public class SortJavaArrayListExample {
 
  public static void main(String[] args) {
   
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("3");
    arrayList.add("5");
    arrayList.add("2");
    arrayList.add("4");
 
    /*
      To sort an ArrayList object, use Collection.sort method. This is a
      static method. It sorts an ArrayList object's elements into ascending order.
    */
    Collections.sort(arrayList);
   
    //display elements of ArrayList
    System.out.println("ArrayList elements after sorting in ascending order : ");
    for(int i=0; i<arrayList.size(); i++)
      System.out.println(arrayList.get(i));
 
  }
}
 
/*
Output would be
ArrayList elements after sorting in ascending order :
1
2
3
4
5
*/
```

#### Example 1:

```java
package com.bb.ilp.tests;

import java.util.ArrayList;
import java.util.Iterator;

import com.bb.ilp.beans.Author;
import com.bb.ilp.beans.Book;

public class SMSTest {

	public static void main(String[] args) {

		

		Book book1 = new Book(1, "Algorithms by ex", "ADA", "Cormen");
		Book book2 = new Book(2, "Data Structures made easy", "Data structures", "Hewitt");
		Book book3 = new Book(3, "Java Complete reference", "Java", "Herbert shield");

		Author author1 = new Author(1, "Cormen", (byte) 26, "Sec 31 ggn", book1);
		Author author2 = new Author(2, "Rahul", (byte) 27, "Sec 17 punjab", book2);
		Author author3 = new Author(3, "Herbert shield", (byte) 35, "Sec 14 delhi", book3);

		//creating Arraylist of Book
		ArrayList<Book> listOfBooks = new ArrayList<>();
		
		//add()
		//Add elements== Object of book type using .add()
		listOfBooks.add(book1);
		listOfBooks.add(book2);
		listOfBooks.add(book3);
		
		//get()
		//Accessing book object using get() starting with index 0
		System.out.println(listOfBooks.get(0).getBookId());
		System.out.println(listOfBooks.get(1).getBookId());
		System.out.println(listOfBooks.get(2).getBookId());
		
		//get() using loop
		//enhancing above code by using for loop
		for(int i=0;i<listOfBooks.size();i++) {
			System.out.println(listOfBooks.get(i).getBookId());
		}
		
		//get using advanced loop
		//using for-each loop
		for(Book book:listOfBooks) {
			System.out.println(book.getBookId());
		}
		
		//get using iterator
		Iterator<Book> iterator=listOfBooks.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next().getBookId());
		}
		
		//removing book with id 2 from the list
		//always use iterator for doing so
		Iterator<Book> iteratorToRemove=listOfBooks.iterator();
		while(iteratorToRemove.hasNext()) {
			if(iteratorToRemove.next().getBookId()==2) {
				iteratorToRemove.remove();
			}
		}
		
		//isEmpty()
		boolean isEmpty=listOfBooks.isEmpty();
		if(isEmpty) {
			System.out.println("List is empty");
		}
		else {
			System.out.println("List is not empty");
		}
		
		//size()
		int size=listOfBooks.size();
		System.out.println("Size of listOfBooks is "+size);
		
		
		//contains()  , to check whether the list contains our book
		if(listOfBooks.contains(book1)) {
			System.out.println("yes it contains");
		}
		else {
			System.out.println("no it doesn't");
		}
		
		//clear is used to remove all the elements
		listOfBooks.clear();
		//now check the whether it is cleared or not by checking size or isEmpty
		if(listOfBooks.isEmpty()) {
			System.out.println("List is empty");
		}
		else {
			System.out.println("List is not empty");
		}
		

	}
}
```

```
1
2
3
1
2
3
1
2
3
1
2
3
List is not empty
Size of listOfBooks is 2
yes it contains
List is empty
```

#### Example 2:

```java
package com;

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

/**
 * Java ArrayList Example Program
 * 
 * @author Mohit
 *
 */
public class Test {

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

		// add example
		letters.add("A");
		letters.add("C");
		letters.add("D");

		// let's insert B between A and C
		letters.add(1, "B");
		System.out.println(letters);

		List<String> list = new ArrayList<String>();
		list.add("E");
		list.add("H");

		// appending list elements to letters
		letters.addAll(list);
		System.out.println(letters);

		// clear example to empty the list
		list.clear();

		list.add("F");
		list.add("G");

		// inserting list inside letters to get right sequence
		letters.addAll(5, list);
		System.out.println(letters);

		// contains example
		System.out.println("Letters list contains E ? " + letters.contains("E"));
		System.out.println("Letters list contains Z ? " + letters.contains("Z"));

		// ensureCapacity example, it's ArrayList method, so object should be defined
		// like below.
		ArrayList<String> tempList = new ArrayList<>();
		tempList.ensureCapacity(1000);

		// get example
		String e = letters.get(4);
		System.out.println("Letter at 5th place: " + e);

		// tempList is empty?
		System.out.println("tempList is empty ? " + tempList.isEmpty());

		// indexOf example
		System.out.println("First index of D = " + letters.indexOf("D"));
		System.out.println("Last index of D = " + letters.lastIndexOf("D"));

		// remove examples
		System.out.println(letters);
		String removed = letters.remove(3);
		System.out.println("After removing '" + removed + "' letters contains " + letters);

		// remove first occurrence of H
		boolean isRemoved = letters.remove("H");
		System.out.println("H removed? " + isRemoved + ". Letters contains " + letters);
		System.out.println("list contains " + list);

		// remove all matching elements between letters and list
		letters.removeAll(list);
		System.out.println(letters);

		// retainAll example
		list.clear();
		list.add("A");
		list.add("B");
		list.add("C");
		letters.retainAll(list);
		System.out.println("letters elements after retainAll operation: " + letters);

		// size example
		System.out.println("letters ArrayList size = " + letters.size());

		// set example
		letters.set(2, "D");
		System.out.println(letters);

		// toArray example
		String[] strArray = new String[letters.size()];
		strArray = letters.toArray(strArray);
		System.out.println(Arrays.toString(strArray));
	}
}
```

```
[A, B, C, D]
[A, B, C, D, E, H]
[A, B, C, D, E, F, G, H]
Letters list contains E ? true
Letters list contains Z ? false
Letter at 5th place: E
tempList is empty ? true
First index of D = 3
Last index of D = 3
[A, B, C, D, E, F, G, H]
After removing 'D' letters contains [A, B, C, E, F, G, H]
H removed? true. Letters contains [A, B, C, E, F, G]
list contains [F, G]
[A, B, C, E]
letters elements after retainAll operation: [A, B, C]
letters ArrayList size = 3
[A, B, D]
[A, B, D]
```

#### Java ArrayList Iterator

Iterator is an interface in [Java Collections framework](broken-reference). ArrayList provides fail-fast iterator implementation. When you want to perform some operation on all the list elements, you should use Iterator. If any structural modification is made to the list while iterating, it’s next() operation will throw ConcurrentModificationException. Below is a simple example of ArrayList iterator.

#### Example 3:

```java
package com;

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

/**
 * Java ArrayList Example Program
 * 
 * @author Mohit
 *
 */
public class Test {

	public static void main(String args[]) {

		List<Integer> ints = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			ints.add(i);
		}

		Iterator<Integer> it = ints.iterator();

		// simple iteration
		while (it.hasNext()) {
			int x = (int) it.next();
			System.out.print(x + ", ");
		}
		System.out.println("\n" + ints);

		// modification of list through iterator
		it = ints.iterator();
		while (it.hasNext()) {
			int x = (int) it.next();
			if (x % 2 == 0) {
				it.remove();
			}
		}
		System.out.println(ints);

		// changing list structure while iterating
		it = ints.iterator();
		while (it.hasNext()) {
			int x = (int) it.next(); // ConcurrentModificationException here
			if (x == 5) {
				ints.add(20);
			}
		}
	}
}
```

```
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.Test.main(Test.java:42)
```

#### Example 4: Copy elements from one arraylist to another:

```java
/*
  Copy Elements of One Java ArrayList to Another Java ArrayList Example
  This java example shows how to copy all elements of one Java ArrayList object to
  another Java ArrayList object using copy method of Collections class.
*/
 
import java.util.ArrayList;
import java.util.Collections;
 
public class CopyElementsOfArrayListToArrayListExample {
 
  public static void main(String[] args) {
     
    //create first ArrayList object
    ArrayList arrayList1 = new ArrayList();
   
    //Add elements to ArrayList
    arrayList1.add("1");
    arrayList1.add("2");
    arrayList1.add("3");
   
    //create another ArrayList object
    ArrayList arrayList2 = new ArrayList();
   
    //Add elements to Arraylist
    arrayList2.add("One");
    arrayList2.add("Two");
    arrayList2.add("Three");
    arrayList2.add("Four");
    arrayList2.add("Five");
   
    /*
      To copy elements of one Java ArrayList to another use,
      static void copy(List dstList, List sourceList) method of Collections class.
     
      This method copies all elements of source list to destination list. After copy
      index of the elements in both source and destination lists would be identical.
     
      The destination list must be long enough to hold all copied elements. If it is
      longer than that, the rest of the destination list's elments would remain
      unaffected.       
    */ 
   
    System.out.println("Before copy, Second ArrayList Contains : " + arrayList2);
   
    //copy all elements of ArrayList to another ArrayList using copy 
    //method of Collections class
    Collections.copy(arrayList2,arrayList1);
   
    /*
      Please note that, If destination ArrayList object is not long 
      enough to hold all elements of source ArrayList, 
      it throws IndexOutOfBoundsException.
    */
 
    System.out.println("After copy, Second ArrayList Contains : " + arrayList2);   
  }
}
 
/*
Output would be
Before copy, Second ArrayList Contains : [One, Two, Three, Four, Five]
After copy, Second ArrayList Contains : [1, 2, 3, Four, Five]
*/
```

#### Example 5: Find maximum element of Java ArrayList.

```java
/*
  Find maxmimum element of Java ArrayList Example
  This java example shows how to find a maximum element of Java ArrayList using
  max method of Collections class.
*/
 
import java.util.ArrayList;
import java.util.Collections;
 
public class FindMaximumOfArrayListExample {
 
  public static void main(String[] args) {
   
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add(new Integer("327482"));
    arrayList.add(new Integer("13408"));
    arrayList.add(new Integer("802348"));
    arrayList.add(new Integer("345308"));
    arrayList.add(new Integer("509324"));
   
    /*
       To find maximum element of Java ArrayList use,
       static Object max(Collection c) method of Collections class.
      
       This method returns the maximum element of Java ArrayList according to
       its natural ordering.
    */
   
    Object obj = Collections.max(arrayList);
   
    System.out.println("Maximum Element of Java ArrayList is : " + obj);
  }
}
 
/*
Output would be
Maximum Element of Java ArrayList is : 802348
*/
```

#### Example 6: Find Minimum element of Java ArrayList

```java
/*
  Find Minimum element of Java ArrayList Example
  This java example shows how to find a minimum element of Java ArrayList using
  min method of Collections class.
*/
 
import java.util.ArrayList;
import java.util.Collections;
 
public class FindMinimumOfArrayListExample {
 
  public static void main(String[] args) {
   
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add(new Integer("327482"));
    arrayList.add(new Integer("13408"));
    arrayList.add(new Integer("802348"));
    arrayList.add(new Integer("345308"));
    arrayList.add(new Integer("509324"));
   
    /*
       To find minimum element of Java ArrayList use,
       static Object min(Collection c) method of Collections class.
      
       This method returns the minimum element of Java ArrayList according to
       its natural ordering.
    */
   
    Object obj = Collections.min(arrayList);
   
    System.out.println("Minimum Element of Java ArrayList is : " + obj);
  }
}
/*
Output would be
Minimum Element of Java ArrayList is : 13408
*/
```

#### Example 7: Swap elements of Java ArrayList

```java
/*
  Swap elements of Java ArrayList example
  This java example shows how to swap elements of Java ArrayList object using
  swap method of Collections class.
*/
 
import java.util.ArrayList;
import java.util.Collections;
 
public class SwapElementsOfArrayListExample {
 
  public static void main(String[] args) {
   
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("C");
    arrayList.add("D");
    arrayList.add("E");
   
    System.out.println("Before swaping, ArrayList contains : " + arrayList);
   
    /*
      To swap elements of Java ArrayList use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.
     
      If the specified positions are equal, list remains unchanged.
     
      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.
    */
   
    Collections.swap(arrayList,0,4);
   
    System.out.println("After swaping, ArrayList contains : " + arrayList);
   
  }
}
 
/*
Output would be
Before swaping, ArrayList contains : [A, B, C, D, E]
After swaping, ArrayList contains : [E, B, C, D, A]
*/
```



###

### Quiz :

{% embed url="https://chortle.ccsu.edu/java5/Notes/chap54/chap54quizRev2.html" %}

### Problems:

**1.** Write a Java program to create a new array list, add some colors (string) and print out the collection. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-1.php)

**2.** Write a Java program to iterate through all elements in a array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-2.php)

**3.** Write a Java program to insert an element into the array list at the first position. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-3.php)

**4.** Write a Java program to retrieve an element (at a specified index) from a given array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-4.php)

**5.** Write a Java program to update specific array element by given element. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-5.php)

**6.** Write a Java program to remove the third element from a array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-6.php)

**7.** Write a Java program to search an element in a array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-7.php)

**8.** Write a Java program to sort a given array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-8.php)

**9.** Write a Java program to copy one array list into another. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-9.php)

**10.** Write a Java program to shuffle elements in a array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-10.php)

**11.** Write a Java program to reverse elements in a array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-11.php)

**12.** Write a Java program to extract a portion of a array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-12.php)

**13.** Write a Java program to compare two array lists. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-13.php)

**14.** Write a Java program of swap two elements in an array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-14.php)

**15.** Write a Java program to join two array lists. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-15.php)

**16.** Write a Java program to clone an array list to another array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-16.php)

**17.** Write a Java program to empty an array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-17.php)

**18.** Write a Java program to test an array list is empty or not. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-18.php)

**19.** Write a Java program to trim the capacity of an array list the current list size. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-19.php)

**20.** Write a Java program to increase the size of an array list. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-20.php)

**21.** Write a Java program to replace the second element of a ArrayList with the specified element. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-21.php)

**22.** Write a Java program to print all the elements of a ArrayList using the position of the elements. [Go to the editor](https://www.w3resource.com/java-exercises/collection/index.php#editorr)\
[Click me to see the solution](https://www.w3resource.com/java-exercises/collection/java-collection-exercise-22.php)

### Coding Challenges :

{% embed url="https://www.hackerrank.com/challenges/java-arraylist/problem" %}

