Javatpoint Logo
Javatpoint Logo

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





Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA