Printing out a Linked list

48,997

Solution 1

If your list implements the java.util.list interface you can use, this line to convert the list to an array and print out the array.

System.out.println(Arrays.toString(list.toArray()));

Solution 2

Well, by default every class in java got toString method from Object class. The toString method from Object class will print class name followed with @ and hash code.

You can override toString method for the LinkedList. For example:

class MyLinkedList extends LinkedList
{

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "MyLinkedList [size=" + size + ", first=" + first + ", last="
                + last + ", modCount=" + modCount + "]";
    }

}

Then you can print it:

 MyLinkedList list = new MyLinkedList ();
 System.out.println(list);

Solution 3

You can derive the linked list class and override the toString method...

Share:
48,997
joe
Author by

joe

Updated on July 05, 2022

Comments

  • joe
    joe almost 2 years

    When I try to print out my linked list of objects it gives me this:

    linkedlist.MyLinkedList@329f3d

    Is there a way to simply overide this to print as Strings?

    package linkedlist;
    
    import java.util.Scanner;
    
    public class LinkedListTest {
    
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            String item;
    
            MyLinkedList list = new MyLinkedList();
            System.out.println("Number of items in the list: " + list.size());
    
            Object item1 = "one";
            Object item2 = "two";
            Object item3 = "Three";
    
            list.add(item1);
            list.add(item2);
            list.add(item3);
    
            System.out.println("Number of items in the list: " + list.size());
    
            System.out.println(list);
    }