List listing

When I try to print a linked list of objects, this gives me the following:

linkedlist.MyLinkedList@329f3d

Is there a way to just override 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); } 
+4
source share
3 answers

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

 System.out.println(Arrays.toString(list.toArray())); 
+10
source

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

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

 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); 
+5
source

You can get the linked list and override the toString method ...

+1
source

All Articles