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
LinkedListis a doubly-linked list implementation of theListandDequeinterfaces. TheLinkedListclass is present in thejava.utilpackage. Read more about theLinkedListhere.
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
LinkedListclass. -
In line 4: We created a new
LinkedListobject with the namelist. -
From lines 5-7: We added three elements (
1,2,3) tolistusing theadd()method. -
In line 8: We used the
toString()method to get the string representation oflist.