Home » Java programming language

Java HashSet add() Method with Example

HashSet Class add() method: Here, we are going to learn about the add() method of HashSet Class with its syntax and example.
Submitted by Preeti Jain, on March 05, 2020

HashSet Class add() method

  • add() method is available in java.util package.
  • add() method is used to insert the given element in this HashSet when not already exists otherwise it ignores it and returns false.
  • add() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • add() method does not throw an exception at the time of adding an element.

Syntax:

    public boolean add(Element ele);

Parameter(s):

  • Element ele – represents the object to be inserted in this HashSet.

Return value:

The return type of the method is boolean, it returns true when the given element (ele) is not already present in this HashSet otherwise it returns false when the given object is already exists in this HashSet.

Example:

// Java program to demonstrate the example 
// of boolean add(Element ele) method of HashSet 

import java.util.*;

public class AddOfHashSet {
    public static void main(String[] args) {
        // Instantiates a HashSet object
        HashSet < String > hs = new HashSet < String > ();

        // By using add() method is to add
        // the given object of this
        // HashSet if not exists
        hs.add("C");
        hs.add("C++");
        hs.add("JAVA");
        hs.add("PHP");
        hs.add("SFDC");

        // Display HashSet 
        System.out.println("HashSet: " + hs);
    }
}

Output

HashSet: [JAVA, C++, C, SFDC, PHP]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.