How to convert an array to ArrayList in java

In the last tutorial we have shared two methods of converting an ArrayList to Array with example. Here we are sharing three different ways to convert an Array to ArrayList. Basically we are converting an String Array to ArrayList of String type.

String array[] to ArrayList<String>

Method 1: Conversion using Arrays.asList()

Syntax:

ArrayList<T> arraylist= new ArrayList<T>(Arrays.asList(arrayname));

Example:

In this example we are using Arrays.asList method to convert the Array to ArrayList.

Method 2: Collections.addAll method

Collections.addAll method all the array elements to the specified collection. This is how Collections.addAll method is being called. It does the same as Arrays.asList method however it is much faster than it so performance wise this is a best way to get the array converted to ArrayList.

If you are using the array as “int[] obj=new int[x];” then it will not work because the array list can be created for the Integer class not the int class so it will return a type mismatch error. so take the array as Integer[] obj=new Integer[x];