AbstractSet add() method in Java with Example
The add(E) method of AbstractSet Class appends the specified element to the end of this AbstractSet.
boolean add(E element)
Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the AbstractSet.
Return Value: This method returns True after successful execution, else False.
Exception: This method throws:
- UnsupportedOperationException: if the add operation is not supported by this collection
- ClassCastException: if the class of the specified element prevents it from being added to this collection
- NullPointerException: if the specified element is null and this collection does not permit null elements
- IllegalArgumentException: if some property of the element prevents it from being added to this collection
- IllegalStateException: if the element cannot be added at this time due to insertion restrictions
Below program illustrates the working of java.util.AbstractSet.add(E element) method:
The AbstractSet is: [10, 20, Geeks, for] The new AbstractSet is: [10, 20, Element, Geeks, Last, for]
Example 2: To demonstrate NullPointerException
The AbstractSet is: [10, 20, 30, 40, 50] Trying to add null java.lang.NullPointerException
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.