Create ArrayList from array

后端 未结 30 1803
遇见更好的自我
遇见更好的自我 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 22:59

    Even though there are many perfectly written answers to this question, I will add my inputs.

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

    New ArrayList can be created in the following ways

    ArrayList arraylist_1 = new ArrayList<>(Arrays.asList(array));
    ArrayList arraylist_2 = new ArrayList<>(
        Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));
    
    // Add through a collection
    ArrayList arraylist_3 = new ArrayList<>();
    Collections.addAll(arraylist_3, array);
    

    And they very well support all operations of ArrayList

    arraylist_1.add(new Element(4)); // or remove(): Success
    arraylist_2.add(new Element(4)); // or remove(): Success
    arraylist_3.add(new Element(4)); // or remove(): Success
    

    But the following operations returns just a List view of an ArrayList and not actual ArrayList.

    // Returns a List view of array and not actual ArrayList
    List listView_1 = (List) Arrays.asList(array);
    List listView_2 = Arrays.asList(array);
    List listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));
    

    Therefore, they will give error when trying to make some ArrayList operations

    listView_1.add(new Element(4)); // Error
    listView_2.add(new Element(4)); // Error
    listView_3.add(new Element(4)); // Error
    

    More on List representation of array link.

提交回复
热议问题