Home » Java programming language

How to convert ArrayList to Array in Java?

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

Converting ArrayList to Array

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

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

toArray() method

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

Syntax:

    public Object[] toArray(){
    }

Parameter(s):

It does not accept any parameter.

Return value:

The return type of this method is Object[], it returns a converted ArrayList to an Array which contains all of the elements in the ArrayList.

Example:

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

import java.util.*;

public class ArrayListToArray {
    public static void main(String[] args) {
        // ArrayList Declaration
        ArrayList arr_list = new ArrayList();

        // By using add() method to add few elements in 
        // ArrayList

        arr_list.add(10);
        arr_list.add(20);
        arr_list.add(30);
        arr_list.add(40);
        arr_list.add(50);

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

        System.out.println();

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

        Object[] arr = arr_list.toArray();

        // Display Array
        System.out.println("Array elements: ");

        for (Object o: arr)
            System.out.println(o);
    }
}

Output

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

Array elements: 
10
20
30
40
50





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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.