📅  最后修改于: 2023-12-03 14:42:15.128000             🧑  作者: Mango
LinkedList is a class in Java that represents a linked list. A linked list is a data structure consisting of a group of nodes in which each node points to the next node in the sequence.
To print a LinkedList in Java, we can use the toString()
method of the LinkedList class or we can traverse the list using a loop and print each element.
toString()
MethodLinkedList<String> linkedList = new LinkedList<>();
linkedList.add("John");
linkedList.add("Mike");
linkedList.add("Lisa");
String linkedListAsString = linkedList.toString();
System.out.println(linkedListAsString);
Output:
[John, Mike, Lisa]
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("John");
linkedList.add("Mike");
linkedList.add("Lisa");
for(String element: linkedList) {
System.out.println(element);
}
Output:
John
Mike
Lisa
In this example, we use a for-each loop to iterate over the elements in the LinkedList and print each element.
We can also use a traditional for loop to traverse the LinkedList:
for(int i = 0; i < linkedList.size(); i++) {
System.out.println(linkedList.get(i));
}
Output:
John
Mike
Lisa
In this example, we use the get()
method of the LinkedList class to retrieve the element at a given index.
Overall, there are multiple ways to print a LinkedList in Java, and the chosen approach depends on the specific requirements of the program.