Home » Java Collection add() Method with Examples

Java Collection add() Method with Examples

by Online Tutorials Library

Java Collection add() method

The add() method of Java Collection Interface inserts the specified element in this Collection. It returns a Boolean value ‘true’, if it succeeds to insert the element in the specified collection else it returns ‘false’.

Syntax

Parameters

The parameter ‘e’ represents the element to be added in the Collection.

Return

The add() method returns a Boolean value ‘true’, if the specified element is not null and this collection has successfully changed as a result of the call.

Throws

The add() 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 allow null elements

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

IllegalStateException- if the element cannot be inserted at this time due to some insertion restrictions

Example 1

Test it Now

Output:

The elements in Collection : [34, 12, 45]  

Example 2

Test it Now

Output:

The elements in Collection : [Anurag, Dhruv, Prena, Bajaj]  

Example 3

Test it Now

Output:

The elements in Collection : [12, null, 0, 5]  

Example 4

Test it Now

Output:

Exception in thread "main" java.lang.NullPointerException  at java.util.concurrent.ConcurrentLinkedQueue.checkNotNull(ConcurrentLinkedQueue.java:920)  at java.util.concurrent.ConcurrentLinkedQueue.offer(ConcurrentLinkedQueue.java:327)  at java.util.concurrent.ConcurrentLinkedQueue.add(ConcurrentLinkedQueue.java:297)  at com.tutorAspire.JavaCollectionAddExample4.main(JavaCollectionAddExample4.java:13)  

If any of the specified element in this queue is null, it will give NullPointerException as described above.

Next TopicJava Collection

You may also like