Array to Collection: Optimized code

前端 未结 10 2157
萌比男神i
萌比男神i 2021-01-31 14:26

Is there a better way of achieving this?

public static List toList(String[] array) {

    List list = new ArrayList(array.length);

          


        
10条回答
  •  天命终不由人
    2021-01-31 15:06

    Arrays.asList(array)
    

    Arrays uses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

    In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

    Update: Thus your Collections.addAll(list, array) becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

提交回复
热议问题