java 11 toArray(IntFunction) default method & example
In this blog post, we will delve into the Java 11 feature - the toArray(IntFunction) method.
DefaulDefault Collection Method - toArray(IntFunction)
With the Java 11 version, a new default method toArray(IntFunction) has been added to the java.util.collection interface.
You can refer to my previous post on default method.
This method is used to dynamically return an array from a collection of objects.
During development, developers often need to convert collections to array types. This method simplifies the process and enhances the developer’s experience.
Syntax:
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
This method takes an IntFunction as input, which is a Functional interface containing only one abstract method.
toArray(IntFunction) Example
This example covers the conversion of a list of strings to an array of strings and the conversion of a set of strings to an array of strings.
The List.of() and Set.of() methods, introduced in Java 10, are used to create Unmodified collections
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class DefaultMethod {
public static void main(String[] args) {
final List<String> numbersList = List.of("One", "Two", "Three", "Four");
System.out.println(Arrays.toString(numbersList.toArray(String[]::new)));
final Set<String> setStrings = Set.of("Kiran", "John", "Frank", "Sai");
System.out.println(Arrays.toString(setStrings.toArray(String[]::new)));
}
}
Output:
[One, Two, Three, Four]
[Sai, John, Frank, Kiran]
Collection existing ToArray Methods
The Collection interface already has a toArray()
method. However, when a null object is passed, the compiler cannot decide and gives a compile error.
The error is: The method toArray(Object[]) is ambiguous for the type Set
. The compiler is ambiguous between toArray(Object[])
and toArray(IntFunction[])
methods.
To resolve this, instead of passing null, cast it as toArray((Object[])null)
. Note that a NullPointerException
is always thrown for both methods.
The Collection interface has the following overloaded methods; the toArray(IntFunction)
method is the default method, and the remaining methods are not.
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
<T> T[] toArray(T[] a);
Object[] toArray();
Conclusion
In conclusion, we have learned about the default static method toArray in the Collection interface introduced in Java 11, along with an example.