Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
ArrayList toArray() method in Java with Examples
Next article icon

ArrayList toArray() method in Java with Examples

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

Declaring toArray() method

public Object[] toArray()

or

public <T> T[] toArray(T[] a)

Parameters: This method either accepts no parameters or it takes an array T[] as a parameter which is the array into which the elements of the list are to be stored if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value: The function returns an array containing all the elements in this list.

Exception: The first overload of this method throws no exceptions. However, the second overload throws the following exceptions:

  • ArrayStoreException: if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
  • NullPointerException if the specified array is null

Examples of Java ArrayList.toArray() method

Example 1 :Converting an ArrayList to an Array using toArray() Method in Java

The following Java program demonstrates how to convert an ArrayList to an array using the toArray() method. This example showcases the basic usage of the ArrayList and how its elements can be retrieved and stored in the array.

Java
// Java Program to illustrate the // ArrayList toArray() method in Java  import java.util.*;  public class GFG {     public static void main(String[] args)     {          // create object of ArrayList         ArrayList<Integer> ArrLis             = new ArrayList<Integer>();          // Add elements         ArrLis.add(32);         ArrLis.add(67);         ArrLis.add(98);         ArrLis.add(100);          // print ArrayList         System.out.println("ArrayList: " + ArrLis);          // Get the array of the elements         // of the ArrayList         // using toArray() method         Object[] arr = ArrLis.toArray();          System.out.println("Elements of ArrayList"                            + " as Array: "                            + Arrays.toString(arr));     } } 

Output
ArrayList: [32, 67, 98, 100] Elements of ArrayList as Array: [32, 67, 98, 100] 

Explanation of the Program:

  • This Java program demonstrates the use of ArrayList's toArray() method to convert its elements into a regular array.
  • First, integers are added to the ArrayList.
  • Then, the toArray() method is called to obtain an array representation of the ArrayList's elements, which is printed using Arrays.toString(arr).

Example 2 : Converting an ArrayList to a Typed Array using toArray(T[]) Method in Java

This Java program demonstrates how to convert an ArrayList of integers into an array of the integers using the toArray(T[]) method. This method is particularly useful when we want to specify the type of the array ensuring the type safety and avoiding the need for the type casting.

Java
// Java Program to illustrate the // ArrayList toArray(T[]) method in Java  import java.util.*;  // Driver Class public class GFG {     // main function     public static void main(String[] args)     {         // create object of ArrayList         ArrayList<Integer> ArrLis             = new ArrayList<Integer>();          // Add elements         ArrLis.add(32);         ArrLis.add(67);         ArrLis.add(98);         ArrLis.add(100);          // print ArrayList         System.out.println(" ArrayList: " + ArrLis);          // Get the array of the elements         // of the ArrayList         // using toArray(T[]) method         Integer arr[] = new Integer[ArrLis.size()];         arr = ArrLis.toArray(arr);          System.out.println(" Elements of ArrayList "                            + "as Array: "                            + Arrays.toString(arr));     } } 

Output
 ArrayList: [32, 67, 98, 100]  Elements of ArrayList as Array: [32, 67, 98, 100] 

Explanation of the Program:

  • This Java program showcases the ArrayList method toArray(T[]), which converts an ArrayList to an array of specified type T.
  • First, integers are added to ArrLis.
  • Then, an Integer array of the same size is initialized and passed to toArray(arr) to obtain the array representation of ArrLis, printed using Arrays.toString(arr).

Next Article
ArrayList toArray() method in Java with Examples

P

ProgrammerAnvesh
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java - util package
  • Java-Arrays
  • Java-Functions
  • Java-ArrayList
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    AbstractSet toArray() method in Java with Example
    The toArray() method of Java AbstractSet is used to form an array of the same elements as that of the AbstractSet. Basically, it copies all the element from a AbstractSet to a new array. Syntax: Object[] arr = AbstractSet.toArray() Parameters: The method does not take any parameters. Return Value: T
    2 min read
    ArrayList size() Method in Java with Examples
    In Java, the size() method is used to get the number of elements in an ArrayList.Example 1: Here, we will use the size() method to get the number of elements in an ArrayList of integers.Java// Java program to demonstrate the use of // size() method for Integer ArrayList import java.util.ArrayList; p
    2 min read
    AbstractSet toArray(T[]) method in Java with Example
    The toArray(T[]) method method of AbstractSet class in Java is used to form an array of the same elements as that of the AbstractSet. It returns an array containing all of the elements in this AbstractSet in the correct order; the run-time type of the returned array is that of the specified array. I
    4 min read
    Arrays asList() Method in Java with Examples
    The Arrays.asList() method in Java is part of the java.util.Arrays class, which is used to convert an array into a fixed-size list. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). Example:Below is a simple example of the Arrays as
    4 min read
    CharArrayWriter toCharArray() method in Java with examples
    The toCharArray() method of the CharArrayWriter class in Java returns a copy of the input data.Syntax: public char[] toCharArray() Parameters: This method does not accept any parameter.Return Value: This method returns a copy of the input data. Below program illustrate the above method: Program 1: J
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences