Home » Java HashSet add() Method with Examples

Java HashSet add() Method with Examples

by Online Tutorials Library

Java HashSet add() Method

The add() is a method of Java HashSet class which adds the specified element to this set if this set contains no element. If it is already contain the element, the call leaves the set unchanged and returns false.

Syntax

Following is the declaration of add() method:

Parameter

Parameter Description Required/Optional
e It is the element which will be added to this set. Required

Returns

The add() method returns true if this set did not already contain the specified element.

Exceptions

NA

Compatibility Version

Java 1.2 and above

Example 1

Test it Now

Output:

Vijay Ravi Ajay 

Example 2

Test it Now

Output:

Hash set Elements: [151, 121, 111] 

Example 3

Test it Now

Output:

Is the insertion successful?? - true Elements of the HashSet: Google Twitter Instagram Facebook 

Example 4

Test it Now

Output:

103 Operating System Galvin Wiley 6 102 Data Communications & Networking Forouzan Mc Graw Hill 4 101 Let us C Yashwant Kanetkar BPB 8 

You may also like