Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

toArray()

Example

Obtain an array from an ArrayList.

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
Object[] carsArray = cars.toArray();
    for(Object item : carsArray) {
      System.out.println(item);
    }
  }
}

Definition and Usage

The toArray() method retrieves an array containing all the items in the list.

If no argument is provided, the returned array will have the Object type. If an array is specified as an argument, the method returns an array with the same data type.

If the argument array is large enough to accommodate all list items, the method directly returns the argument after populating it with the list items.

Syntax

Choose one of the following: 

public Object[] toArray()
public T[] toArray(T[] array)

“T” denotes the data type of the elements in the list.

Parameter Values

Parameter

Description

array

This parameter is optional. If provided, it determines the data type of the returned array. If the provided array has enough space to accommodate all list items, it will be returned. Otherwise, a new array of the same data type will be created and returned.

Technical Details

Returns:

An array that includes all elements of the ArrayList, arranged in their original order.

Throws:

ArrayStoreException occurs if the type of the array is incompatible with the type of the ArrayList.

NullPointerException is thrown if the argument is null.

More Examples

Example

Define the return type of toArray().

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    String[] carsArray = new String[4];
    carsArray = cars.toArray(carsArray);
    for(String item : carsArray) {
      System.out.println(item);
   }
  }
}