Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out a Linked list [duplicate]

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);
}
like image 934
joe Avatar asked Mar 07 '13 23:03

joe


People also ask

Can LinkedList have duplicate values?

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.

How do you remove consecutive duplicates in a linked list?

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.


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 out the array.

System.out.println(Arrays.toString(list.toArray()));
like image 136
Simulant Avatar answered Oct 04 '22 08:10

Simulant


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);
like image 39
Iswanto San Avatar answered Oct 04 '22 09:10

Iswanto San


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

like image 41
Chen Kinnrot Avatar answered Oct 04 '22 08:10

Chen Kinnrot