What is the LinkedList.toString method in Java?

The toString() method will return the string representation of the LinkedList object with the string representation of each element in the list.

In Java, a LinkedList is a doubly-linked list implementation of the List and Deque interfaces. The LinkedList class is present in the java.util package. Read more about the LinkedList here.

Syntax

public String toString()

Parameters

This method doesn’t take any arguments.

Return value

This method returns a string. This string contains the elements of the list in the insertion order enclosed between [] and separated by a comma. Internally, the elements are converted to string using the String.valueOf(Object) method.

Code

The code below demonstrates how the toString() method can be used.

import java.util.LinkedList;
class LinkedListAdd {
public static void main( String args[] ) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list.toString());
}
}

Explanation

  • In line 1: We imported the LinkedList class.

  • In line 4: We created a new LinkedList object with the name list.

  • From lines 5-7: We added three elements (1,2,3) to list using the add() method.

  • In line 8: We used the toString() method to get the string representation of list.

Free Resources