addAll(Collection): This method is available in java.util.TreeSet class of Java.
Syntax:
boolean java.util.TreeSet.addAll(Collection<? extends String> c)
This method takes one argument. This method adds all of the elements in the specified collection to this set.
Parameters: One parameter is required for this method.
c: a collection containing elements to be added to this set.
Returns: true if this set changed as a result of the call.
Throws:
1. ClassCastException - if the elements provided cannot be compared with the elements currently in the set.
2. NullPointerException - if the specified collection is null or if any element is null and this set uses natural ordering, or its comparator does not permit null elements
Approach 1: When no exception
Java
import java.util.TreeSet;public class TreeSetaddAll {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();TreeSet<String> c = new TreeSet<String>();c.add("Hello");c.add("Java");System.out.println(treeSet.addAll(c));}}
Output:
true
Approach 2: NullPointerException
Java
import java.util.TreeSet;public class TreeSetaddAll {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();TreeSet<String> c = null;System.out.println(treeSet.addAll(c));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.size()" because "c" is null at java.base/java.util.TreeSet.addAll(TreeSet.java:300)
No comments:
Post a Comment