Fastest way to get the first n elements of a List into an Array

后端 未结 5 1927
囚心锁ツ
囚心锁ツ 2020-12-30 20:51

What is the fastest way to get the first n elements of a list stored in an array?

Considering this as the scenario:

int n = 10;
ArrayList

        
5条回答
  •  长发绾君心
    2020-12-30 21:13

    Option 1 Faster Than Option 2

    Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

    String[] out = new String[n];
    for(int i = 0; i < n; i++) {
        out[i] = in.get(i);
    }
    

提交回复
热议问题