CopyOnWriteArrayList
is a thread-safe implementation of ArrayList
, which does not require synchronization.CopyOnWriteArrayList
is duplicated on to 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 the data simultaneously.CopyOnWriteArrayList
isn’t the appropriate data structure to use because the extra copies will almost always result in poor performance.set()
is an instance method of the CopyOnWriteArrayList
, which is used to replace the element at the specified position in the CopyOnWriteArrayList
with the given element.
The set
method is defined in the CopyOnWriteArrayList
class. The CopyOnWriteArrayList
class is defined in the java.util.concurrent
package. To import the CopyOnWriteArrayList
class, we check the following import statement:
import java.util.concurrent.CopyOnWriteArrayList;
public E set(int index, E element)
int index
: This is the index of the element that needs to be replaced.E element
: This is the new element that needs to be stored at the given index.This method returns the previous element at the specified position.
import java.util.concurrent.CopyOnWriteArrayList;public class Main {public static void main(String[] args){CopyOnWriteArrayList<String> copyOnWriteArrayListObject = new CopyOnWriteArrayList<>();copyOnWriteArrayListObject.add("edpresso");copyOnWriteArrayListObject.add("educative");copyOnWriteArrayListObject.add("coding-interview");copyOnWriteArrayListObject.add("courses");System.out.println("List before modification - " + copyOnWriteArrayListObject);int index = 2;String newElement = "hello-world";String previousElement = copyOnWriteArrayListObject.set(index, newElement);System.out.printf("The previous element at index %s is '%s'.\n", index, previousElement);System.out.println("List after modification - " + copyOnWriteArrayListObject);}}
CopyOnWriteArrayList
class.CopyOnWriteArrayList
class and call it copyOnWriteArrayListObject
.copyOnWriteArrayListObject
, using the add()
method.copyOnWriteArrayListObject
.index
at which the element has to be replaced.newElement
that needs to be stored.set()
method to replace the element at the index
with the newElement
. Then, the old element at the index
called previousElement
is returned.previousElement
found at the index
.copyOnWriteArrayListObject
list.