Let’s see some sample programs on how to convert Array to ArrayList

Sample Program 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package classFiveArrays;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
 
public class ConvertArrayToArrayList {
public static void main (String [] args){
//Using asList
String[] students = {“Raj”, “Kumar”, “Rajkumar”};
ArrayList<String> arrList = new ArrayList<>(Arrays.asList(students));
arrList.add(“Ramesh”);
arrList.add(“Bala”);
System.out.println(arrList);
System.out.println(arrList.get(2));
}
 
}

Output:

1
2
3
[Raj, Kumar, Rajkumar, Ramesh, Bala]
Rajkumar
[Raj, Kumar, Rajkumar, Ramesh, Bala]

Sample Program 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package classFiveArrays;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
 
public class ConvertArrayToArrayList {
public static void main (String [] args){
//Using Collection.addAll
String[] students = {“Raj”, “Kumar”, “Rajkumar”};
ArrayList<String> arrList = new ArrayList<String>();
Collections.addAll(arrList, students);
arrList.add(“Hello”);
System.out.println(arrList);
}
 
}

Output:

1
[Raj, Kumar, Rajkumar, Hello]

Sample Program 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package classFiveArrays;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
 
public class ConvertArrayToArrayList {
public static void main (String [] args){
    ArrayList<String> arrList= new ArrayList<String>();
    String array[] = {“Raj”,“Kumar”,“Rajkumar”};  
 
    //array.length returns the current number of elements present in array
    for(int i =0;i<array.length;i++)
            {
     //We are adding each array’s element to the ArrayList
     arrList.add(array[i]);
    }
    
    System.out.println(arrList);
    
    /*ArrayList content*/
    for(String str: arrList)
    {
         System.out.println(str);
    }
}
 
}

Output:

1
2
3
4
[Raj, Kumar, Rajkumar]
Raj
Kumar
Rajkumar

Must Read: Java Tutorial