Java Set toArray()方法及示例
Java Set 的 toArray() 方法是用来形成一个与Set相同元素的数组。基本上,它将Set中的所有元素复制到一个新的数组中。
语法:
Object[] toArray()
参数: 该方法需要可选的参数。例如:set.toArray(new Integer[0])返回一个Integer类型的数组,我们也可以用set.toArray(new Integer[size])
来做,其中size是结果数组的大小。用前一种方式操作,因为所需的大小是内部分配的。
返回值: 该方法返回一个包含类似于Set的元素的数组。
以下程序说明了Set.toArray()方法:
程序1:
// Java code to illustrate toArray()
import java.util.*;
public class SetDemo {
public static void main(String args[])
{
// Creating an empty Set
Set<String> abs_col = new HashSet<String>();
// Use add() method to add
// elements into the Set
abs_col.add("Welcome");
abs_col.add("To");
abs_col.add("Geeks");
abs_col.add("For");
abs_col.add("Geeks");
// Displaying the Set
System.out.println("The Set: "
+ abs_col);
// Creating the array and using toArray()
Object[] arr = abs_col.toArray();
System.out.println("The array is:");
for (int j = 0; j < arr.length; j++)
System.out.println(arr[j]);
}
}
输出
The Set: [Geeks, For, Welcome, To]
The array is:
Geeks
For
Welcome
To
示例2:
// Java code to illustrate toArray()
import java.util.*;
public class SetDemo {
public static void main(String args[])
{
// Creating an empty Set
Set<Integer> abs_col = new HashSet<Integer>();
// Use add() method to add
// elements into the Set
abs_col.add(10);
abs_col.add(15);
abs_col.add(30);
abs_col.add(20);
abs_col.add(5);
abs_col.add(25);
// Displaying the Set
System.out.println("The Set: " + abs_col);
// Creating the array and using toArray()
Integer[] arr = abs_col.toArray(new Integer[0]);
System.out.println("The array is:");
for (int j = 0; j < arr.length; j++)
System.out.println(arr[j]);
}
}
输出
The Set: [20, 5, 25, 10, 30, 15]
The array is:
20
5
25
10
30
15
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray()