Create ArrayList from array

后端 未结 30 1848
遇见更好的自我
遇见更好的自我 2020-11-21 22:29

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this

30条回答
  •  后悔当初
    2020-11-21 23:09

    If you use :

    new ArrayList(Arrays.asList(myArray));
    

    you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[] array each time the capacity needs to be extended.

    Fortunately the JDK implementation is fast and Arrays.asList(a[]) is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.

    // in Arrays
    @SafeVarargs
    public static  List asList(T... a) {
        return new ArrayList<>(a);
    }
    //still in Arrays, creating a private unseen class
    private static class ArrayList
    
        private final E[] a;    
        ArrayList(E[] array) {
            a = array; // you point to the previous array
        }
        ....
    }
    

    The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.

    If not, the most understandable way is to do this :

    ArrayList list = new ArrayList(myArray.length); // you know the initial capacity
    for (Element element : myArray) {
        list.add(element);
    }
    

    Or as said @glglgl, you can create another independant ArrayList with :

    new ArrayList(Arrays.asList(myArray));
    

    I love to use Collections, Arrays, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.

提交回复
热议问题