Home » Java programming language

How to convert Array to ArrayList in Java?

Converting Array to ArrayList: Here, we are going to learn how to convert an Array into ArrayList in Java programming?
Submitted by Preeti Jain, on September 10, 2019

Converting Array to ArrayList

Given an Array, and we have to convert it into ArrayList in Java.

To convert an Array to ArrayList, we use asList() method.

asList() method

  • asList() method is available in java.util package.
  • asList() method is used to convert an Array to ArrayList.
  • asList() method returns a converted List object which contains all of the elements in the Array.
  • asList() method does not throw any exception at the time of conversion from Array to ArrayList.
  • It's a static method, it is accessible with the class name too. (i.e. If we try to execute with the class name then we will not get an error).
  • It's not a final method; it is overridable in child class if we want.

Syntax:

    public static List asList(array_name){
    }

Parameter(s):

array_name – represents the name of an array by which the list of the elements will be backed.

Return value:

The return type of this method is List, it returns the list view of the given array.

Example:

// Java program to demonstrate the example of
// conversion of an Array to an ArrayList with 
// the help of asList() method of Arrays

import java.util.*;

public class ArrayToArrayList {
    public static void main(String[] args) {
        // array declaration
        Integer arr[] = {
            10,
            20,
            30,
            40,
            50
        };

        // Display array elements 
        System.out.println("Array elements");
        for (int i = 0; i < arr.length; ++i)
            System.out.println(arr[i]);

        System.out.println();

        // By using asList() method is used to convert 
        // Array to ArrayList

        List arr_list = Arrays.asList(arr);

        // Display ArrayList
        System.out.println("ArrayList Elements:");
        System.out.println(arr_list);
    }
}

Output

Array elements
10
20
30
40
50

ArrayList Elements:
[10, 20, 30, 40, 50]





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.