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

Retrieve an array from a LinkedList:

import java.util.LinkedList;

 

public class Main {

  public static void main(String[] args) {

    LinkedList cars = new LinkedList();

    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 elements from the list.

If no argument is provided, the returned array type will be Object. However, if an array is specified as an argument, the method will return an array of the same type.

If the provided array is large enough to accommodate all list elements, the method populates it with the list items and returns the same array.

Syntax

Choose one from the following:

public Object[] toArray()

public T[] toArray(T[] array)

T represents the data type of items in the list.

Parameter Values

Parameter

Description

array

Optional. An array which specifies the data type of the returned array and will be returned by the method if it has enough space for the items in the list. If the array is not large enough then the method returns a new array of the same data type.

 

 

 

 

 

 

 

Technical Details

Returns:

An array containing all of the elements of the LinkedList in order.

Throws:

ArrayStoreException – If the type of the array is not compatible with the type of the LinkedList.
NullPointerException – If the argument is null.

More Examples

Example

Define the return type of toArray():
import java.util.LinkedList;
public class Main {
 public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<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);
    }
 }
}