Java : CopyOnWriteArraySet with Examples

CopyOnWriteArraySet (Java SE 19 & JDK 19) API Examples.
You will find code examples on most CopyOnWriteArraySet methods.


Summary

A Set that uses an internal CopyOnWriteArrayList for all of its operations. Thus, it shares the same basic properties: It is best suited for applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to prevent interference among threads during traversal. It is thread-safe.

Class diagram

void test(Set<Integer> set) throws InterruptedException {
    for (int i = 0; i < 5; i++) {
        set.add(i);
    }

    try (final var executor = Executors.newSingleThreadScheduledExecutor()) {

        executor.schedule(() -> {
            System.out.println("-- add value! --");
            set.add(9999);
        }, 5, TimeUnit.SECONDS);

        try {
            for (final var value : set) {
                System.out.println("value = " + value);
                TimeUnit.SECONDS.sleep(2);
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("ConcurrentModificationException!");
        }
    }

    System.out.println("-- end --");
    System.out.println("set = " + set);
}
test(new LinkedHashSet<>());

// Result
// ↓
//value = 0
//value = 1
//value = 2
//-- add value! --
//ConcurrentModificationException!
//-- end --
//set = [0, 1, 2, 3, 4, 9999]

test(new CopyOnWriteArraySet<>());

// Result
// ↓
//value = 0
//value = 1
//value = 2
//-- add value! --
//value = 3
//value = 4
//-- end --
//set = [0, 1, 2, 3, 4, 9999]

Constructors

CopyOnWriteArraySet ()

Creates an empty set.

final var set = new CopyOnWriteArraySet<String>();
System.out.println(set); // []
System.out.println(set.isEmpty()); // true

set.add("a");
set.add("b");
set.add("c");

System.out.println(set); // [a, b, c]
System.out.println(set.size()); // 3

CopyOnWriteArraySet (Collection<? extends E> c)

Creates a set containing all of the elements of the specified collection.

final var c = List.of("a", "b", "c");

final var set = new CopyOnWriteArraySet<>(c);
System.out.println(set); // [a, b, c]
System.out.println(set.size()); // 3

Methods

boolean add (E e)

Adds the specified element to this set if it is not already present.

final var set = new CopyOnWriteArraySet<String>();
System.out.println(set); // []

System.out.println(set.add("a")); // true
System.out.println(set); // [a]

System.out.println(set.add("b")); // true
System.out.println(set); // [a, b]

System.out.println(set.add("c")); // true
System.out.println(set); // [a, b, c]

System.out.println(set.add("a")); // false
System.out.println(set); // [a, b, c]

boolean addAll (Collection<? extends E> c)

Adds all of the elements in the specified collection to this set if they're not already present.

final var src = List.of("a", "b", "c");

{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.addAll(List.of("d", "e", "f"))); // true
    System.out.println(set);  // [a, b, c, d, e, f]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.addAll(List.of("a", "b", "c"))); // false
    System.out.println(set); // [a, b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.addAll(List.of("a", "c", "e", "f"))); // true
    System.out.println(set); // [a, b, c, e, f]
}

void clear ()

Removes all of the elements from this set.

final var set = new CopyOnWriteArraySet<String>();
System.out.println(set); // []

set.add("a");
System.out.println(set); // [a]

set.add("b");
System.out.println(set); // [a, b]

set.clear();
System.out.println(set); // []

boolean contains (Object o)

Returns true if this set contains the specified element.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

System.out.println(set.contains("")); // false
System.out.println(set.contains("a")); // true
System.out.println(set.contains("b")); // true
System.out.println(set.contains("c")); // true

System.out.println(set.contains("X")); // false
System.out.println(set.contains("abc")); // false

boolean containsAll (Collection<?> c)

Returns true if this set contains all of the elements of the specified collection.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

System.out.println(set.containsAll(Set.of())); // true

System.out.println(set.containsAll(Set.of("a"))); // true
System.out.println(set.containsAll(Set.of("a", "b"))); // true
System.out.println(set.containsAll(Set.of("b", "a"))); // true
System.out.println(set.containsAll(Set.of("c", "b", "a"))); // true

System.out.println(set.containsAll(Set.of("X"))); // false
System.out.println(set.containsAll(Set.of("a", "X"))); // false
System.out.println(set.containsAll(Set.of("a", "b", "c", "X"))); // false

boolean equals (Object o)

Compares the specified object with this set for equality.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

System.out.println(set.equals(Set.of("a"))); // false
System.out.println(set.equals(Set.of("a", "b"))); // false
System.out.println(set.equals(Set.of("a", "b", "c"))); // true
System.out.println(set.equals(Set.of("c", "b", "a"))); // true
final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

final var hashSet = new HashSet<>(set);
System.out.println(hashSet); // [a, b, c]
System.out.println(set.equals(hashSet)); // true

final var treeSet = new TreeSet<>(set);
System.out.println(treeSet); // [a, b, c]
System.out.println(set.equals(treeSet)); // true

final var list = new ArrayList<>(set);
System.out.println(list); // [a, b, c]
System.out.println(set.equals(list)); // false

void forEach (Consumer<? super E> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "aaa", "bbb", "ccc");
System.out.println(set); // [aaa, bbb, ccc]

System.out.println("-- forEach --");
set.forEach(element -> {
    System.out.println(element);
});

// Result
// ↓
//-- forEach --
//aaa
//bbb
//ccc

boolean isEmpty ()

Returns true if this set contains no elements.

final var set = new CopyOnWriteArraySet<String>();
set.add("a");
set.add("b");
set.add("c");

System.out.println(set); // [a, b, c]
System.out.println(set.isEmpty()); // false

set.clear();
System.out.println(set); // []
System.out.println(set.isEmpty()); // true

Iterator<E> iterator ()

Returns an iterator over the elements contained in this set in the order in which these elements were added.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "aaa", "bbb", "ccc");
System.out.println(set); // [aaa, bbb, ccc]

System.out.println("-- iterator --");
set.iterator().forEachRemaining(System.out::println);

// Result
// ↓
//-- iterator --
//aaa
//bbb
//ccc

boolean remove (Object o)

Removes the specified element from this set if it is present.

final var src = List.of("a", "b", "c");

{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.remove("")); // false
    System.out.println(set); // [a, b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.remove("a")); // true
    System.out.println(set); // [b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.remove("b")); // true
    System.out.println(set); // [a, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.remove("X")); // false
    System.out.println(set); // [a, b, c]
}

boolean removeAll (Collection<?> c)

Removes from this set all of its elements that are contained in the specified collection.

final var src = List.of("a", "b", "c");

{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of())); // false
    System.out.println(set); // [a, b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of("a"))); // true
    System.out.println(set); // [b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of("a", "b"))); // true
    System.out.println(set); // [c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of("b", "a"))); // true
    System.out.println(set); // [c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of("a", "b", "c"))); // true
    System.out.println(set); // []
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of("X", "Y"))); // false
    System.out.println(set); // [a, b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.removeAll(Set.of("a", "X"))); // true
    System.out.println(set); // [b, c]
}

boolean removeIf (Predicate<? super E> filter)

Removes all of the elements of this collection that satisfy the given predicate.

final var set = new CopyOnWriteArraySet<String>();
set.add("aaa");
set.add("BBB");
set.add("ccc");
set.add("DDD");

System.out.println(set); // [aaa, BBB, ccc, DDD]

final var ret = set.removeIf(s -> {
    return s.equals(s.toUpperCase());
});

System.out.println(ret); // true
System.out.println(set); // [aaa, ccc]
final var set = new CopyOnWriteArraySet<String>();
set.add("aaa");
set.add("bbb");

System.out.println(set); // [aaa, bbb]

final var ret = set.removeIf(s -> s.equals(s.toUpperCase()));

System.out.println(ret); // false
System.out.println(set); // [aaa, bbb]

boolean retainAll (Collection<?> c)

Retains only the elements in this set that are contained in the specified collection.

final var src = List.of("a", "b", "c");

{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of())); // true
    System.out.println(set); // []
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("a"))); // true
    System.out.println(set); // [a]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("a", "b"))); // true
    System.out.println(set); // [a, b]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("b", "a"))); // true
    System.out.println(set); // [a, b]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("a", "b", "c"))); // false
    System.out.println(set); // [a, b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("a", "b", "c", "X", "Y"))); // false
    System.out.println(set); // [a, b, c]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("X", "a", "b", "Y"))); // true
    System.out.println(set); // [a, b]
}
{
    final var set = new CopyOnWriteArraySet<>(src);
    System.out.println(set); // [a, b, c]

    System.out.println(set.retainAll(Set.of("X", "Y"))); // true
    System.out.println(set); // []
}

int size ()

Returns the number of elements in this set.

final var set1 = new CopyOnWriteArraySet<String>();
System.out.println(set1); // []
System.out.println(set1.size()); // 0

final var set2 = new CopyOnWriteArraySet<String>();
Collections.addAll(set2, "a", "b", "c");
System.out.println(set2); // [a, b, c]
System.out.println(set2.size()); // 3

Spliterator<E> spliterator ()

Returns a Spliterator over the elements in this set in the order in which these elements were added.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "aaa", "bbb", "ccc");
System.out.println(set); // [aaa, bbb, ccc]

final var spliterator = set.spliterator();
spliterator.forEachRemaining(System.out::println);

// Result
// ↓
//aaa
//bbb
//ccc

Object[] toArray ()

Returns an array containing all of the elements in this set.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

final Object[] array = set.toArray();
System.out.println(Arrays.toString(array)); // [a, b, c]

<T> T[] toArray (T[] a)

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

final String[] ret = set.toArray(new String[0]);
System.out.println(Arrays.toString(ret)); // [a, b, c]
final var set = new CopyOnWriteArraySet<String>();
Collections.addAll(set, "a", "b", "c");
System.out.println(set); // [a, b, c]

{
    final String[] array = new String[3];
    System.out.println(Arrays.toString(array)); // [null, null, null]

    final var ret = set.toArray(array);
    System.out.println(Arrays.toString(array)); // [a, b, c]
    System.out.println(Arrays.toString(ret)); // [a, b, c]
}
{
    final String[] array = new String[5];
    System.out.println(Arrays.toString(array)); // [null, null, null, null, null]

    final var ret = set.toArray(array);
    System.out.println(Arrays.toString(array)); // [a, b, c, null, null]
    System.out.println(Arrays.toString(ret)); // [a, b, c, null, null]
}
{
    final String[] array = new String[1];
    System.out.println(Arrays.toString(array)); // [null]

    final var ret = set.toArray(array);
    System.out.println(Arrays.toString(array)); // [null]
    System.out.println(Arrays.toString(ret)); // [a, b, c]
}

Methods declared in AbstractSet

hashCode

Please see the link below.

Methods declared in AbstractCollection

toString

Please see the link below.

Methods declared in Collection

parallelStream, stream, toArray

Please see the link below.


Related posts

To top of page