Java program to convert a HashSet into an array

Given a HashSet, we have to convert it into an array.
Submitted by Nidhi, on May 10, 2022

Problem Solution:

In this program, we will create a set using the HashSet collection to store integer elements. Then we will convert the created HashSet into an object array using the toArray() method.

Program/Source Code:

The source code to convert a HashSet into an array is given below. The given program is compiled and executed successfully.

// Java program to convert a HashSet 
// into an array

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashSet < Integer > nums = new HashSet();

    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);
    nums.add(5);
    nums.add(6);

    Object arr[] = nums.toArray();

    System.out.println("Array elements: ");
    for (Object item: arr)
      System.out.print(item + " ");
  }
}

Output:

Array elements: 
1 2 3 4 5 6

Explanation:

In the above program, we imported the "java.util.*" package to use the HashSet collection. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. Here, we created a set nums to store integer data elements using HashSet collection. Then we converted the nums set into an array using the toArray() method and assigned it to the arr array. After that, we printed the elements of the array.

Java HashSet Programs »






Comments and Discussions!

Load comments ↻






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