Convert Java Array to ArrayList in Java using different approaches?

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. We can also add all the arrayâ??s element to the array list manually.As the second part of program shows.


								
package com.mindclues;

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListExample {

    public static void main(String[] args) {

        /* Array Declaration and initialization*/
        String charArr[] = {"A", "B", "C", "D"};

        /*Array to ArrayList conversion*/
        ArrayList charList = new ArrayList();

        /*Adding new elements to the converted List*/
        charList.add("E");
        charList.add("F");

        /*Final ArrayList content display using for*/
        System.out.println("List before add array");
        for (String str : charList) {
            System.out.println(str);
        }
        //Add array To ArrayList
        Collections.addAll(charList, charArr);
        System.out.println(" ");
        System.out.println("List after add array");
        for (String str : charList) {
            System.out.println(str);
        }

          //Second part for program show the manual way to convert array to arraylist
        for (int i = 0; i < charArr.length; i++) {

            /* We are adding each array's element to the ArrayList*/
            charList.add(charArr[i]);
        }
        System.out.println("mannal way to add Array element to ArrayList");
        for (String str : charList) {
            System.out.println(str);
        }
    }
}


							

								
List before add array
E
F
 
List after add array
E
F
A
B
C
D
mannal way to add Array element to ArrayList
E
F
A
B
C
D
A
B
C
D
							

Related Articles

post a comment