In this post we will see how to add elements in CopyOnWriteArrayList using below 2 methods
1. boolean add(E e)
Appends the specified element to the end of this list.
2. void add(int index, E element)
Inserts the specified element at the specified position in this list.
In the below code we will do the following
1. Create a copyOnWriteArrayList object
2. Add 4 elements using add(E e) method
3. Print the added elements
4. Add 2 more elements at index 2 and 3 using add(int index, E element)
5. Print the entire object
Code for Add elements in CopyOnWriteArrayList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.kscodes.collections.samples; import java.util.concurrent.CopyOnWriteArrayList; public class CopyOnWriteArrayListAddEx { public static void main(String[] args) { // Create a copyOnWriteArrayList object CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>(); // Adding 4 elements using add() method copyOnWriteArrayList.add("Zero"); copyOnWriteArrayList.add("One"); copyOnWriteArrayList.add("Two"); copyOnWriteArrayList.add("Three"); // Printing the added elements System.out.println(copyOnWriteArrayList); // Now adding 2 elements at index 2 and 3. copyOnWriteArrayList.add(2, "NewTwo"); copyOnWriteArrayList.add(3, "NewThree"); // Again printing the elements to see if the elements were added at the // given index. System.out.println(copyOnWriteArrayList); } } |