You can convert arrays to ArrayList by using this method:
1 2 3 |
new ArrayList<Type>(Arrays.asList(array)) |
1. Convert Integer array to ArrayList
1 2 3 4 5 |
Integer[] integerArray = {8, 14, 9}; ArrayList<Integer> integerList = new ArrayList<Integer>(Arrays.asList(integerArray)); System.out.println(integerList); |
In the first line of above code, we declare an array of Integers. In the second line, we convert this array into ArrayList. Lastly, we print the integerList.
The output of the above program is:
1 2 3 |
[8, 14, 9] |
2. Convert String array to ArrayList
When it comes to Strings the things are very similar. You can see it in this example:
1 2 3 4 5 |
String[] stringArray = { "first", "second", "third" }; ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(stringArray)); System.out.println(stringList); |
1 2 3 |
[first, second, third] |
3. Convert primitive type array to ArrayList
Next, we will consider arrays which have primitive types.
1 2 3 4 5 6 7 8 |
int[] intArray = {3, 7, 5}; List<Integer> integerList = new ArrayList<>(); for (int intValue : intArray) { integerList.add(intValue); } System.out.println(integerList); |
1 2 3 |
[3, 7, 5] |