HashSet toArray() in Java

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

Syntax:

Object[] java.util.HashSet.toArray()

This method returns an array containing all of the elements in this set.

Parameters: NA

Returns: an array containing all the elements in this set.

Exceptions: NA

Approach

Java

import java.util.Arrays;
import java.util.HashSet;

public class HashSettoArray {
    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(Arrays.toString(hashSet.toArray()));
    }
}

Output:

[Java, C++, Hello]


No comments:

Post a Comment