How to Get an Array of All LinkedList Elements in Java


In this example, we’ll learn how to get an Object array from elements of LinkedList with toArray method in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedList;

public class GetObjectArrayOfLinkedList {

	public static void main(String[] args) {

		LinkedList ll = new LinkedList();

		ll.add(1);
		ll.add(2);
		ll.add(3);
		ll.add(4);

		// Use the toArray() method to get an Object array of all the elements
		// on the LinkedList
		Object[] nums = ll.toArray();

		for (Object num : nums) {
			System.out.println(num);
		}

	}

}

Output:

1
2
3
4

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments