Array to Collection: Optimized code

前端 未结 10 2009
萌比男神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 14:44

    What do you mean by better way:

    more readable:

    List list = new ArrayList(Arrays.asList(array));
    

    less memory consumption, and maybe faster (but definitely not thread safe):

    public static List toList(String[] array) {
        if (array==null) {
           return new ArrayList(0);
        } else {
           int size = array.length;
           List list = new ArrayList(size);
           for(int i = 0; i < size; i++) {
              list.add(array[i]);
           }
           return list;
        }
    }
    

    Btw: here is a bug in your first example:

    array.length will raise a null pointer exception if array is null, so the check if (array!=null) must be done first.

提交回复
热议问题