Convert Array to ArrayList in Java


How to Convert String Array to ArrayList in Java

Array in Java is a fixed length data structure, whose size when defined cannot be changed. Whereas ArrayList in Java is a variable length Collection class, whose size gets changed as we add new element in it.

Array is faster than ArrayList because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows(exceeds its actual size defined at start). It creates a new Array and copies every element from the old one to the new one. This is the reason programmers prefer Array over ArrayList. But in real life applications, there is always a need to convert Array to ArrayList. This can be done directly by using inbuilt java function to convert String Array to ArrayList.

Syntax for converting String Array to ArrayList:

List<String> a = new ArrayList<String>(Arrays.asList(StringObject));

Example for converting to ArrayList from Array:

import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class ArrayToArrayList { public static void main(String[] args) { String[] str = {"Solution","Factory"}; List<String> a = new ArrayList<String>(Arrays.asList(str)); System.out.println(a); } }

Solution Worked 2 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote



Search Tags

    Array to ArrayList in Java

    ArrayList from Array in Java