Asked 7 years ago
5 Jan 2017
Views 988

posted

how to convert array to ArrayList

convert array ---> ArrayList

suppose array is defined like this

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


now want to convert array to ArrayList Class object

ArrayList<Element> arraylist = array;

whether it auto type conversion array to ArrayList or any conversion method or what ?
ajamil

ajamil
answered Apr 24 '23 00:00

To convert an array to an ArrayList in Java, you can create a new ArrayList and pass the array as an argument to the ArrayList constructor.

Here's an example:



String[] array = {"apple", "banana", "cherry", "date"};

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

In this example, we have an array of strings called array with four elements. To convert this array to an ArrayList , we create a new ArrayList called arrayList and pass the array as an argument to the Arrays.asList() method. This method returns a List object that is then used to initialize the arrayList.

Note that the type of the ArrayList must match the type of the array. In this example, we have a String array, so we create an ArrayList<String>.

After running the code, the arrayList object will contain the same elements as the array.

It's important to note that the Arrays.asList() method returns a fixed-size list backed by the original array. This means that any modifications made to the ArrayList will also affect the original array. If you need to create a new, independent ArrayList, you can create a new ArrayList and add the elements of the array using a loop or the Collections.addAll( ) method.
Post Answer