An efficient way to convert List<Integer> to int[] ( array ) without iteration

Tim Florian :
  public static int[] convertListToArray(List<Integer> listResult) {
        int[] result = new int[listResult.size()];
        int i= 0;
        for (int num : listResult) {
            result[i++] = num;
        }
        return result;
    }

Is there an efficient way to convert List to array without iterating List explicitly ? Maybe it is possible by using methods like:

Arrays.copyOf(int [] origin , int newLength );
System.arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

I know that there is a solution described here. However, I particularly interested in an efficient way of converting List<Integer> to int[]

T.J. Crowder :

Given the need to convert from Integer to int, I don't think you're going to find something more efficient than what you have, if I assume you're talking about runtime efficiency.

You might find converting to Integer[] first and then looping might be more efficient (below), but you might not, too. You'd have to test it in your specific scenario and see.

Here's that example:

int size = listResult.size();
int[] result = new int[size];
Integer[] temp = listResult.toArray(new Integer[size]);
for (int n = 0; n < size; ++n) {
    result[n] = temp[n];
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=449778&siteId=1