Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is CopyOnWriteArrayList.addAll method() in Java?

abhilash

What is CopyOnWriteArrayList?

  • The CopyOnWriteArrayList is a thread-safe implementation of ArrayList without the requirement for synchronization.
  • The whole content of the CopyOnWriteArrayList is duplicated into a new internal copy when we use any of the altering methods, such as add() or delete(). Hence, the list can be iterated in a safe way, without any fear of losing data, while modifying it simultaneously.
  • The data structure’s properties make it particularly helpful in situations when we iterate it more frequently than we alter it.
  • If adding items is a typical activity, CopyOnWriteArrayList isn’t the appropriate data structure to use as the extra copies will almost always result in poor performance.

addAll() is an instance method of the CopyOnWriteArrayList which is used to insert all the elements in the given collection to the end of the list. The order of insertion of the elements at the end of the list is the order in which the elements are returned by the iterator of the specified collection.

The addAll() method is defined in the CopyOnWriteArrayList class. The CopyOnWriteArrayList class is defined in the java.util.concurrent package. To import the CopyOnWriteArrayList class, check the following import statement.

import java.util.concurrent.CopyOnWriteArrayList;

Syntax


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

Parameters

  • Collection<? extends E> c: The collection to append to the list.

Return value

This method returns true if the list is changed/modified. Otherwise, it returns false.

Code

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Main{

    public static void main(String[] args) {
        // Create the CopyOnWriteArrayList object
        CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();

        // add element to copyOnWriteArrayList
        copyOnWriteArrayList.add("inital-value");

        // collection to add to the copyOnWriteArrayList
        List<String> stringList = Arrays.asList("hello", "educative");

        // print the list before addAll operation
        System.out.println("List before addAll operation - " + copyOnWriteArrayList);

        // addAll operation to add the contents of the list to copyOnWriteArrayList
        boolean addAllReturnValue = copyOnWriteArrayList.addAll(stringList);

        // Return value of the addAll operation
        System.out.println("Return value of the addAll operation - " + addAllReturnValue);

        // print the list after addAll operation
        System.out.println("List after addAll operation - " + copyOnWriteArrayList);
    }
}
Calling CopyOnWriteArrayList.addAll() method

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring