这是将HashSet
转换为数组的程序。
程序
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);
}
}
}
输出:
HashSet contains: [Element1, Element2, Element3, Element4]
Array elements:
Element1
Element2
Element3
Element4