6

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);
}
joe
  • 385
  • 6
  • 9
  • 17
  • can you show us some code? – Ron Mar 07 '13 at 23:59
  • What have you tried so far and what programming language you use. However, a related question is http://stackoverflow.com/questions/4372976/c-print-linked-list-of-strings – Mihai8 Mar 07 '13 at 23:59

3 Answers3

11

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()));
Simulant
  • 19,190
  • 8
  • 63
  • 98
5

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);
Iswanto San
  • 18,263
  • 13
  • 58
  • 79
1

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

Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141