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
LinkedListis a doubly-linked list implementation of theListandDequeinterfaces. TheLinkedListclass is present in thejava.utilpackage. Read more about theLinkedListhere.
public String toString()
This method doesn’t take any arguments.
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.
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());}}
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.