Array to Collection: Optimized code

前端 未结 10 2025
萌比男神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<String> list = new ArrayList<String>(Arrays.asList(array));
    

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

    public static List<String> toList(String[] array) {
        if (array==null) {
           return new ArrayList(0);
        } else {
           int size = array.length;
           List<String> 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.

    0 讨论(0)
  • 2021-01-31 14:46

    Yes, there is. You can use the Arrays class from the java.util.* package. Then it's actually just one line of code.

    List<String> list = Arrays.asList(array);
    
    0 讨论(0)
  • 2021-01-31 14:48

    What about :

    List myList = new ArrayList(); 
    String[] myStringArray = new String[] {"Java", "is", "Cool"}; 
    
    Collections.addAll(myList, myStringArray); 
    
    0 讨论(0)
  • 2021-01-31 14:56

    You can try something like this:

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

    public ArrayList(Collection c)

    Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.

    Taken from here

    0 讨论(0)
  • 2021-01-31 14:57

    Have you checked Arrays.asList(); see API

    0 讨论(0)
  • 2021-01-31 15:01

    You can use:

    list.addAll(Arrays.asList(array));
    
    0 讨论(0)
提交回复
热议问题