HashSet addAll(Collection) in Java

addAll(Collection): This method is available in java.util.HashSet 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.HashSet;

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

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");
        HashSet<String> hashSet2 = new HashSet<String>();

        hashSet2.addAll(hashSet);

        System.out.println(hashSet2);

    }
}

Output:

[Java, C++, Hello]


Approach 2: NullPointerException 

Java

import java.util.HashSet;

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

        HashSet<String> hashSet = null;
        HashSet<String> hashSet2 = new HashSet<String>();

        hashSet2.addAll(hashSet);

        System.out.println(hashSet2);

    }
}

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