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);
}
A LinkedList can store the data by use of the doubly Linked list. Each element is stored as a node. The LinkedList can have duplicate elements because of each value store as a node.
Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.
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()));
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);
You can derive the linked list class and override the toString method...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With