add() method

add() method: This add method in java utilizes to add the given element in collection.

boolean add(E e);

Where, E represents the type of elements in collection.
e is the element which you want to add in this collection.
return type:  Its return type is boolean. It can return either true or false.

How add() method can work: We have different types of collections like ArrayList, HashSet etc. Each collection has some set of rules. Some collection doesn’t allow duplicate elements, but some are allowing. So, the add() method can behave differently and it works according to the class in which it is implemented.

For example: The add() method in java is implemented in Hashset class is not able to add any duplicate element in Hashset. Because Hashset doesn’t supports the duplicate elements.But the add() method behaves different for the ArrayList class because it is also implemented in ArrayList class and ArrayList can add the duplicate elements.

This method can throw different types of exceptions:
UnsupportedOperationException, If the add operation is not allowed in 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 the collection does not allow null elements.
IllegalArgumentException, if some property of the element prevents it from being added to this collection.
IllegalStateException, If the element can’t be added at this time due to insertion restrictions.

2 thoughts on “add() method”

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.