Home » Java programming language

Java LinkedList Object[] toArray() method with Example

Java LinkedList Object[] toArray() method: Here, we are going to learn about the Object[] toArray() method of LinkedList class with its syntax and example.
Submitted by Preeti Jain, on June 24, 2019

LinkedList Object[] toArray() method

  • This method is available in package java.util.Collection and here, Collection is an interface.
  • This method is declared in interface Collection and implemented by the LinkedList Class.
  • This method is used to return a whole array and the array contains all of the element of the linked list.
  • This method returns an array of objects or elements.

Syntax:

    Object[] toArray(){
    }

Parameter(s):

This method does not accept any parameter but it returns an array of the Linked List.

Return value:

The return type of this method is Object[] that means this method returns an array of all the elements that is represented in the linked list.

Java program to demonstrate example of LinkedList toArray() method

import java.util.LinkedList;

class LinkList {
    public static void main(String[] args) {

        // Create an object of linked list 
        LinkedList list = new LinkedList();

        // use add() method to add few elements in the linked list 
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);

        //  Current Linked list Output
        System.out.println("The  Current Linked List is :" + list);

        // create an array for objects and copy the linked list to it
        Object[] arr = list.toArray();

        // Traverse the array
        for (int i = 0; i < list.size(); ++i) {
            System.out.println("The element at index " + i + " " + "is :" + arr[i]);
        }
    }
}

Output

D:\Programs>javac LinkList.java

D:\Programs>java LinkList
The  Current Linked List is :[10, 20, 30, 40, 50]
The element at index 0 is :10
The element at index 1 is :20
The element at index 2 is :30
The element at index 3 is :40
The element at index 4 is :50


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.