Reputation: 8421
Given that I have a list of objects like below:
import java.util.List;
List<Protocol> protocolsTestData
and i wish to convert this list to array of with same type like Protocol[]
.
Then i can use the following code:
Protocol[] protocolsTestDataArray = new Protocol[protocolsTestData.size()];
protocolsTestData.toArray(protocolsTestDataArray);
However, the above code only works with type Protocol
but i need to have generic function which converts a list with any type to a an array with the same type!
Upvotes: 1
Views: 563
Reputation: 109557
The following is succinct and optimal.
Protocol[] protocolsTestDataArray = protocolsTestData.toArray(new Protocol[0]);
You do not need to optimize creating a correctly sized array, as meanwhile the JVM byte code of the above is even faster than your code. For any generic solution one still need to pass the array constructor.
The Stream version:
Protocol[] protocolsTestDataArray = protocolsTestData.stream()
.toArray(Protocol[]::new);
A (superfluous) generic function:
public static <A> A[] toArray(List<A> list, IntFunction<A[]> generator) {
return list.toArray(generator.apply(list.size()));
}
Protocol[] protocolsTestDataArray = toArray(protocolsTestData, Protocol[]::new);
The function needs to know the actual A[]
constructor as the information on A is lacking (java's type erasure).
Upvotes: 1