在这篇博文中,我们将学习Java 11的特性--toArray(IntFunction)方法。
默认的收集方法 - toArray(IntFunction)
在Java 11版本中,java.util.collection接口中加入了新的默认方法toArray(IntFunction)。你可以查看我之前关于默认方法的文章。这个方法用于动态地从一个对象集合中返回数组。在开发过程中,开发者需要将集合转换为数组类型,这将缓解和简化开发者的生活。
签名
default T[] toArray(IntFunction generator) {
return toArray(generator.apply(0));
}
这个方法的输入是IntFunction-功能性接口,只包含一个抽象方法。
ToArray(IntFunction) 示例
这个例子涵盖了以下内容
- 如何将字符串列表转换为字符串数组
- 如何将字符串集转换为字符串数组
在Java 10中引入的List.of()和Set.of()方法可以创建未经修改的集合
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class DefaultMethod {
public static void main(String[] args) {
final List numbersList = List.of("One", "Two", "Three", "Four");
System.out.println(Arrays.toString(numbersList.toArray(String[]::new)));
final Set setStrings = Set.of("Kiran", "John", "Frank", "Sai");
System.out.println(Arrays.toString(setStrings.toArray(String[]::new)));
}
}
输出是
[One, Two, Three, Four]
[Sai, John, Frank, Kiran]
集合现有的ToArray方法
集合接口已经有了toArray()方法,编译器无法决定当一个空对象被传递时,会产生编译错误 toArray(Object[])方法对Set类型是模糊的。原因是编译器在选择toArray(Object[])和toArray(IntFunction[])方法时产生了歧义。用toArray((Object[])null)来代替null,就可以了。对于这两个方法,总是抛出NullPointerException。
集合接口有以下重载方法,toArray(IntFunction)方法是默认方法,其余方法不是。
default T[] toArray(IntFunction generator) {
return toArray(generator.apply(0));
}
T[] toArray(T[] a);
Object[] toArray();