LinkedHashSet toArray(T) method in Java with Example
The toArray(T) method method of LinkedHashSet class in Java is used to form an array of the same elements as that of the LinkedHashSet. It returns an array containing all of the elements in this LinkedHashSet in the correct order; the run-time type of the returned array is that of the specified array. If the LinkedHashSet fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the run time type of the specified array and the size of this LinkedHashSet.
If the LinkedHashSet fits in the specified array with room to spare (i.e., the array has more elements than the LinkedHashSet), the element in the array immediately following the end of the LinkedHashSet is set to null. (This is useful in determining the length of the LinkedHashSet only if the caller knows that the LinkedHashSet does not contain any null elements.)
public <T> T toArray(T a)
Parameters: The method accepts one parameter arr which is the array into which the elements of the LinkedHashSet are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Return Value: The method returns an array containing the elements similar to the LinkedHashSet.
Exception: The method might throw two types of exception:
- ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the LinkedHashSet.
- NullPointerException: If the array is Null, then this exception is thrown.
Below program illustrates the working of the LinkedHashSet.toArray(arr) method.
Program 1: When array is of the size of LinkedHashSet
The LinkedHashSet: [Welcome, To, Geeks, For] The arr is: Welcome To Geeks For null
Program 2: When array is less than the size of LinkedHashSet
The LinkedHashSet: [Welcome, To, Geeks, For] The arr is: Welcome To Geeks For
Program 3: When array is more than the size of LinkedHashSet
The LinkedHashSet: [Welcome, To, Geeks, For] The arr is: Welcome To Geeks For null null null null null null
Program 4: To demonstrate NullPointerException
The LinkedHashSet: [Welcome, To, Geeks, For] Exception: java.lang.NullPointerException
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.