简体   繁体   中英

How to convert List of any object to an array with the same type?

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!

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM