原文: https://beginnersbook.com/2014/08/converting-a-hashset-to-an-array/

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

程序

  1. import java.util.HashSet;
  2. class ConvertHashSettoArray{
  3. public static void main(String[] args) {
  4. // Create a HashSet
  5. HashSet<String> hset = new HashSet<String>();
  6. //add elements to HashSet
  7. hset.add("Element1");
  8. hset.add("Element2");
  9. hset.add("Element3");
  10. hset.add("Element4");
  11. // Displaying HashSet elements
  12. System.out.println("HashSet contains: "+ hset);
  13. // Creating an Array
  14. String[] array = new String[hset.size()];
  15. hset.toArray(array);
  16. // Displaying Array elements
  17. System.out.println("Array elements: ");
  18. for(String temp : array){
  19. System.out.println(temp);
  20. }
  21. }
  22. }

输出:

  1. HashSet contains: [Element1, Element2, Element3, Element4]
  2. Array elements:
  3. Element1
  4. Element2
  5. Element3
  6. Element4