Core Java

Java LinkedList toString() Print Example

The LinkedList class in Java is a part of the java.util package and provides a way to store ordered elements in a linked list structure. Printing a LinkedList efficiently is crucial for debugging and understanding its contents. Java provides a built-in toString() method that can be used to print the elements in a readable format. Let us delve into understanding how Java’s LinkedList utilizes toString() for printing its elements.

1. What is the LinkedList?

A LinkedList in Java is a part of the Java Collections Framework and is implemented in the java.util package. It is a doubly linked list that allows elements to be stored in non-contiguous memory locations. Each element in a LinkedList is called a node, and each node contains two parts:

  • Data – The actual value stored in the node.
  • References (Pointers) – Links to the previous and next nodes in the list.

1.1 Features of LinkedList in Java

  • Implements List, Queue, and Deque interfaces.
  • Allows duplicate elements.
  • Supports insertion and deletion operations faster than an ArrayList because it does not require shifting elements.
  • Uses more memory than an ArrayList due to extra space for pointers.

2. toString() Method in LinkedList

The toString() method in Java is inherited from the AbstractCollection class and overridden in LinkedList to provide a string representation of the list. By default, toString() returns a string representation of the elements enclosed in square brackets, separated by commas.

2.1 How does toString() work?

When we print a LinkedList object, Java internally calls toString() to convert the LinkedList into a human-readable format.

01
02
03
04
05
06
07
08
09
10
11
12
import java.util.LinkedList;
 
public class LinkedListToStringExample {
  public static void main(String[] args) {
    LinkedList < String > names = new LinkedList < > ();
    names.add("Alice");
    names.add("Bob");
    names.add("Charlie");
 
    System.out.println(names.toString());
  }
}

2.1.1 Code Explanation and Output

The given Java program demonstrates how to use the toString() method to print the contents of a LinkedList. It first imports and initializes a LinkedList of type String named names, then adds three elements: “Alice,” “Bob,” and “Charlie.” Since LinkedList inherits the toString() method from the AbstractCollection class, calling System.out.println(names.toString()) (or simply System.out.println(names)) automatically converts the list into a string representation formatted as [Alice, Bob, Charlie], which is then printed to the console.

1
[Alice, Bob, Charlie]

3. Customize the toString() method

If you are using a custom class inside a LinkedList, overriding toString() is useful for better representation.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.LinkedList;
 
class Student {
  String name;
  int age;
 
  public Student(String name, int age) {
    this.name = name;
    this.age = age;
  }
 
  @Override
  public String toString() {
    return name + " (Age: " + age + ")";
  }
}
 
public class CustomToStringExample {
  public static void main(String[] args) {
    LinkedList < Student > students = new LinkedList < > ();
    students.add(new Student("Alice", 22));
    students.add(new Student("Bob", 24));
 
    System.out.println(students);
  }
}

3.1 Code Explanation and Output

The given Java code defines a Student class with two attributes: name (a string) and age (an integer), along with a parameterized constructor to initialize these values. The toString() method is overridden to return a custom string representation of a student in the format name (Age: age). In the CustomToStringExample class, a LinkedList of Student objects is created, and two student objects (Alice and Bob) are added to it. When the System.out.println(students) statement is executed, the overridden toString() method is automatically invoked for each Student object, resulting in an output like [Alice (Age: 22), Bob (Age: 24)].

1
[Alice (Age: 22), Bob (Age: 24)]

4. Best Practices of using toString() method

  • Use toString() for quick debugging but avoid using it in production logs unless necessary.
    • Example: System.out.println(object.toString()); can help inspect object values during development.
    • Potential issue: If an object has a complex structure, toString() might not provide useful information.
  • Override toString() in custom objects for better readability.
    • Example:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      class Person {
      String name;
      int age;
       
      @Override
      public String toString() {
      return "Person{name='" + name + "', age=" + age + "}";
      }
      }
    • Helps in logging meaningful information instead of default memory addresses.
  • If handling large lists, consider iterating manually for better formatting and performance.
    • Example: Instead of System.out.println(list.toString());, iterate manually:
      1
      2
      3
      for (Person p : peopleList) {
      System.out.println(p);
      }
    • Avoids performance issues with large collections and prevents truncation of data in logs.

5. Conclusion

The toString() method in LinkedList provides a simple way to print elements. While useful for debugging, overriding it in custom classes enhances clarity. In large-scale applications, consider structured logging instead of toString() for better performance.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button