声明一个HashSet并添加元素-
Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91); hs.add(93); hs.add(97); hs.add(99);
要复制所有元素,请使用toArray()方法-
Object[] obArr = hs.toArray();
以下是将所有元素复制到HashSet到对象数组的示例-
import java.util.*;
public class Demo {
public static void main(String args[]) {
Set<Integer> hs = new HashSet<Integer>();
hs.add(15);
hs.add(71);
hs.add(82);
hs.add(89);
hs.add(91);
hs.add(93);
hs.add(97);
hs.add(99);
System.out.println("Elements in set = "+hs);
System.out.println("Copying all elements...");
Object[] obArr = hs.toArray();
for (Object ob : obArr)
System.out.println(ob);
}
}输出结果
Elements in set = [97, 82, 99, 71, 89, 91, 93, 15] Copying all elements... 97 82 99 71 89 91 93 15