The method can create an array with all the objects in the Set collection.
Syntax 1 generates an array of the same length, based on the size of the set collection, which contains all the contents of the set collection.
ToArray ()
The example saves all the contents of the set collection into a new array.
public static void Main (string[] args) {
Set set = new HashSet (); Defining Set Collection Objects
Set.add ("Apple"); To add an object to the collection
Set.add ("Computer");
Set.add ("book");
Set.add (New Date ());
object[] ToArray = Set.toarray (); Gets the array form of the collection
System.out.println ("The length of the array is:" +toarray.length); Output array length
}
The run result is "the length of the array is: 4".
Syntax 2 stores all the contents of the set collection using the specified array.
ToArray (t[] a)
A: is an array that holds all the contents of the set collection.
For the return value, if the parameter specifies an array that holds all the contents of the set collection, the array is used to hold all the objects in the set collection and returns the array, otherwise a new array that holds all the contents of the set collection is returned.
If the length of the array specified by the parameter is greater than the size of the set collection, all remaining space of the array is copied to a null value.
Typical application This example outputs all the contents of a set collection to an array that exceeds the size of the set collection. Partial content beyond the set collection is replaced with NULL, as shown in result 1.33.
The key code for this example is as follows:
public static void Main (string[] args) {
Set set = new HashSet (); Defining set Sets
Set.add ("Apple"); To add an object to the collection
Set.add ("Computer");
Set.add ("book");
Set.add ("String is also an object, not a basic data type");
string[] Strarray = new String[6]; Defines a string array of length 6
String[] ToArray = (string[]) Set.toarray (Strarray); Converts a collection to a string array form
System.out.println ("The length of the array is:" + toarray.length); Output array length
for (string string:toarray) {//Iterate through a string array
System.out.println (string); Output string array contents
}
}