gpt4 book ai didi

java - 为什么没有 toArray(Class)?

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:30 27 4
gpt4 key购买 nike

为什么 List 中没有 toArray 变体,它只接受一个类型,例如:

Foo[] array = list.toArray(Foo.class);
// or
Foo[] array = list.toArray(Foo[].class);

我见过

// existing array
Foo[] array = list.toArray(array);
// Fake array
Foo[] array = list.toArray(new Foo[0]);

但是当我只想指定类型而不是创建一个不必要的一次性数组时,创建一个空数组对我来说似乎效率低下且违反直觉。

最佳答案

从界面的角度来看,我同意。

该方法只需要类型(除了副作用),因此只要求类型是合适的。

我猜主要原因是效率。仅采用类型的实现速度明显较慢,但我没有检查实现细节(参见 .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])? 和博客 Arrays of Wisdom of the Ancients 中的基准)。

但是请注意,自 Java 11 以来我们得到了一个新变体,它更接近您想要的,也更适合这种情况:

toArray(Foo[]::new)

来自其documentation :

Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Use toArray() to create an array whose runtime type is Object[], or use toArray(T[]) to reuse an existing array.

The default implementation calls the generator function with zero and then passes the resulting array to toArray(T[]).

该方法不需要反射,因为您直接提供生成器。

总而言之,现在你应该使用

  • toArray()如果你想要 Object[] (很少适用),
  • toArray(T[])如果您想重用现有数组(应该足够大),
  • toArray(IntFunction<T[]>)如果你想要类型安全和一个新数组。

关于java - 为什么没有 toArray(Class<T>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com