LinkedHashSet addAll(Collection) in Java

addAll(Collection): This method is available in java.util.LinkedHashSet class of Java.

Syntax:

boolean java.util.AbstractCollection.addAll(Collection<? extends K> c)

This method takes one argument. This method adds all of the elements in the specified collection to this collection.

Parameters: One parameter is required for this method.

c: a collection containing elements to be added to this collection.

Returns: true if this collection changed as a result of the call.

Throws:

1. UnsupportedOperationException - if the addAll operation is not supported by this collection.

2. ClassCastException - if the class of an element of the specified collection prevents it from being added to this collection.

3. NullPointerException - if the specified collection contains a null element and this collection does not permit null elements, or if the specified collection is null.

4. IllegalArgumentException - if some property of an element of the specified collection prevents it from being added to this collection.

5. IllegalStateException - if not all the elements can be added at this time due to insertion restrictions.

Approach 1: When no exception

Java

import java.util.Collection;
import java.util.LinkedHashSet;

public class LinkedHashSetaddAll {
    public static void main(String[] args) {

        LinkedHashSet<String> linkedHashSet =
new LinkedHashSet<>();

        Collection<String> collection =
new LinkedHashSet<String>();
        collection.add("Java");
        collection.add("C++");
        linkedHashSet.add("Hello");
        linkedHashSet.addAll(collection);
        System.out.println(linkedHashSet);

    }
}

Output:

[Hello, Java, C++]


Approach 2: NullPointerException

Java

import java.util.Collection;
import java.util.LinkedHashSet;

public class LinkedHashSetaddAll {
    public static void main(String[] args) {

        LinkedHashSet<String> linkedHashSet =
new LinkedHashSet<>();

        Collection<String> collection = null;
        linkedHashSet.add("Hello");
        linkedHashSet.addAll(collection);
        System.out.println(linkedHashSet);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.iterator()" because "c" is null at java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:335)


No comments:

Post a Comment