Java程序将Set转换为数组
Set对象提供一种称为的方法toArray()。此方法接受一个空数组作为参数,将当前Set转换为数组并将其放置在给定数组中。要将Set对象转换为数组-
创建一个Set对象。
向其添加元素。
创建一个具有创建的Set大小的空数组。
使用toArray()方法将Set转换为数组,并绕过上面创建的数组作为其参数。
打印数组的内容。
示例
import java.util.HashSet;
import java.util.Set;
public class SetToArray {
public static void main(String args[]){
Set<String> set = new HashSet<String>();
set.add("Apple");
set.add("Orange");
set.add("Banana");
System.out.println("Contents of Set ::"+set);
String[] myArray = new String[set.size()];
set.toArray(myArray);
for(int i=0; i<myArray.length; i++){
System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]);
}
}
}输出结果
Contents of Set ::[Apple, Orange, Banana] Element at the index 1 is ::Apple Element at the index 2 is ::Orange Element at the index 3 is ::Banana
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短