Java Collection add() methodThe 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'. SyntaxParametersThe parameter 'e' represents the element to be added in the Collection. ReturnThe 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. ThrowsThe 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 1Test it NowOutput: The elements in Collection : [34, 12, 45] Example 2Test it NowOutput: The elements in Collection : [Anurag, Dhruv, Prena, Bajaj] Example 3Test it NowOutput: The elements in Collection : [12, null, 0, 5] Example 4Test it NowOutput: 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.javaTpoint.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 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India