# 将`HashSet`转换为数组

> 原文： [https://beginnersbook.com/2014/08/converting-a-hashset-to-an-array/](https://beginnersbook.com/2014/08/converting-a-hashset-to-an-array/)

这是将`HashSet`转换为数组的程序。

#### 程序

```java
import java.util.HashSet;
class ConvertHashSettoArray{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();

     //add elements to HashSet
     hset.add("Element1");
     hset.add("Element2");
     hset.add("Element3");
     hset.add("Element4");

     // Displaying HashSet elements
     System.out.println("HashSet contains: "+ hset);

     // Creating an Array
     String[] array = new String[hset.size()];
     hset.toArray(array);

     // Displaying Array elements
     System.out.println("Array elements: ");
     for(String temp : array){
        System.out.println(temp);
     }
  }
}
```

**输出：**

```java
HashSet contains: [Element1, Element2, Element3, Element4]
Array elements: 
Element1
Element2
Element3
Element4
```