Site icon JavaGoal

How to convert linked list to array in java

We have read, a lot of things about LinkedList in java. In this post, we will see how to convert a LinkedList to Array.
We know Array works on based of index and LinkedList works based on doubly linked list structure. Let’s see How to convert linked list to array in java, there are some methods for conversion.

1. toArray() method
2. toArray(T[] a)
3. get() method

Object[] toArray() method

We can use toArray() method to convert a LinkedList to Array in java. This method returns an array of objects that contains all the elements of the LinkedList. It maintains the order of elements as in LinkedList. It is the most common and popular way to convert LinkedList to array in java.

public Object[] toArray()

accessModifier, Here public keyword specifies the access of method, it can be accessed from any class.
return type, It returns an array of Object, and Object class is super most class of Java.
parameter, It doesn’t take any parameter.

import java.util.LinkedList;
public class LinkedListExample 
{
    public static void main(String arg[])
    {
        LinkedList<String> listOfNames = new LinkedList<String>();
        listOfNames.add("JAVA");
        listOfNames.add("GOAL");
        listOfNames.add("LEARNING");
        listOfNames.add("WEBSITE");
        
        LinkedList<Integer> listOfNumber = new LinkedList<Integer>();
        listOfNumber.add(123);
        listOfNumber.add(456);
        listOfNumber.add(789);
        
        // It returning array of Object type
        Object[] namesArray =  listOfNames.toArray();
        System.out.println("String Array:");
        for(Object obj : namesArray)
            System.out.println(obj);
        
        // It returning array of Object type
        Object[] numberArray =  listOfNumber.toArray();
        System.out.println("Integer Array:");
        for(Object obj : numberArray)
            System.out.println(obj);
    }
}

Output: String Array:
JAVA
GOAL
LEARNING
WEBSITE
Integer Array:
123
456
789

Note: The toArray() method returns an array of type Object that is Object[].Here Object is topmost class so we need to typecast it. If we do not typecast, the compiler throws the compilation error. Let’s see the example of how it will work?

import java.util.LinkedList;

public class ExampleOfLinkedList 
{
    public static void main(String arg[])
    {
        LinkedList<String> listOfNames = new LinkedList<String>();
        listOfNames.add("JAVA");
        listOfNames.add("GOAL");
        listOfNames.add("LEARNING");
        listOfNames.add("WEBSITE");
        
        LinkedList<Integer> listOfNumber = new LinkedList<Integer>();
        listOfNumber.add(123);
        listOfNumber.add(456);
        listOfNumber.add(789);
        
        // It returning array of Object type
        String[] namesArray =  (String[]) listOfNames.toArray();
        System.out.println("String Array:");
        for(String obj : namesArray)
        	System.out.println(obj);
        
        // It returning array of Object type
        Integer[] numberArray =  (Integer[]) listOfNumber.toArray();
        System.out.println("Integer Array:");
        for(Integer obj : numberArray)
        	System.out.println(obj);
    }
}

Output: Exception in thread “main” java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader ‘bootstrap’) at ArrayListExample.main(ArrayListExample.java:18)

As you can see, Here compiler throwing ClassCastException, Because we are trying to convert an object of child class(String or Integer) to object of the parent class(Object). To resolve this problem we can use toArray(T[] a) method.

toArray(T[] a) method

The toArray(T[] a) method and toArray() method works similarly except the return type and parameter. This method takes an argument of Array. This method accepts an object array and fills that array with the objects of LinkedList. If ​the size of the given array is greater than or equal to the size of the ArrayList, then the toArray(T[] a) method fills the elements of the ArrayList in array. Otherwise, it creates a new array and filled up.

public T[] toArray(T[] a)

accessModifier, The method has public access modifier, so it can be accessed from any class.
return type, it returns an array of T type. Where T is the object of Arrays which programmer wants to return.
parameter, It takes an object of Array.
Exception, ArrayStoreException is thrown if any element in the list fails to be​ converted into the specified type.

import java.util.LinkedList;

public class ExampleOfLinkedList 
{
    public static void main(String arg[])
    {
        LinkedList<String> listOfNames = new LinkedList<String>();
        listOfNames.add("JAVA");
        listOfNames.add("GOAL");
        listOfNames.add("LEARNING");
        listOfNames.add("WEBSITE");
        
        LinkedList<Integer> listOfNumber = new LinkedList<Integer>();
        listOfNumber.add(123);
        listOfNumber.add(456);
        listOfNumber.add(789);
        
        
        String[] namesArray = new String[listOfNames.size()];
        // It returning array of Object type
        namesArray =  listOfNames.toArray(namesArray);
        System.out.println("String Array: ");
        for(String s : namesArray)
        	System.out.println(s);
        

        Integer[] numbersArray = new Integer[listOfNumber.size()];
        // It returning array of Object type
        numbersArray =  listOfNumber.toArray(numbersArray);
        System.out.println("Integer Array: ");
        for(Integer num : numbersArray)
        	System.out.println(num);
    }
}

Output: String Array:
JAVA
GOAL
LEARNING
WEBSITE
Integer Array:
123
456
789

get(int index) method

If you don’t want to use the toArray() method, you can use get() method and convert the ArrayList to Array. Let’s see how to convert linked list to array in java

import java.util.LinkedList;
public class ExampleOfLinkedList 
{
    public static void main(String arg[])
    {
        LinkedList<String> listOfNames = new LinkedList<String>();
        listOfNames.add("JAVA");
        listOfNames.add("GOAL");
        listOfNames.add("LEARNING");
        listOfNames.add("WEBSITE");
        
        LinkedList<Integer> listOfNumber = new LinkedList<Integer>();
        listOfNumber.add(123);
        listOfNumber.add(456);
        listOfNumber.add(789);
        
        String[] namesArray = new String[listOfNames.size()];
        for (int i = 0; i < listOfNames.size(); i++) 
        	namesArray[i] = listOfNames.get(i); 
        
        System.out.println("String Array: ");
        for(String s : namesArray)
        	System.out.println(s);    
    }
}

Output: String Array:
JAVA
GOAL
LEARNING
WEBSITE

Exit mobile version