HashSet add(K) in Java

add(K): This method is available in java.util.HashSet class of Java.

Syntax:

boolean java.util.HashSet.add(K e)

This method takes one argument. This method adds the specified element to this set if it is not already present.

Parameters: One parameter is required for this method.

e: the element to be added to this set.

Returns: true if this set did not already contain the specified element.

Exceptions: NA

Approach

Java

import java.util.HashSet;

public class HashSetadd {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        System.out.println(hashSet);

    }
}

Output:

[Java, C++, Hello]


No comments:

Post a Comment