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

后端 未结 5 1854
囚心锁ツ
囚心锁ツ 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:25

    Option 3

    Iterators are faster than using the get operation, since the get operation has to start from the beginning if it has to do some traversal. It probably wouldn't make a difference in an ArrayList, but other data structures could see a noticeable speed difference. This is also compatible with things that aren't lists, like sets.

    String[] out = new String[n];
    Iterator iterator = in.iterator();
    for (int i = 0; i < n && iterator.hasNext(); i++)
        out[i] = iterator.next();
    

提交回复
热议问题