0

I have a class called (a) which contains (int x) and (Date d) so i want to sort the linked list due to date by a method i already made which takes l (LL stores date) and m (LL stores class a) then printing it but it prints out like this:package1.test0$a@2f4d3709.

   package package1
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import eg.edu.alexu.csd.datastructure.linkedList.csxx_csyy.DoubleLinkedList;
import eg.edu.alexu.csd.datastructure.Stack;

public abstract class test0 {
    static class a{
        Date d ;
        int x ;
    }

    public static void main(String[] args) throws ParseException {
        a k = new a() ; //first object

        a k1 = new a() ; //2nd object

        DoubleLinkedList m = new DoubleLinkedList() ;
        DoubleLinkedList l = new DoubleLinkedList() ;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");
        k.d = date2 ;            
        k.x = 1 ;    
        l.add(k.d);    // add in date LL
        m.add(k);      // add in integer and date LL
        k1.d = date1 ;
        l.add(k1.d);
        k1.x = 10 ;
        m.add(k1);
        m.print();    // print before sorting
        Sort s = new Sort() ;
        s.sortdate(l,m);       //sort by date
        m.print();    //print after sorting



    }

}

1 Answers1

1

You have to override the toString() method, which belongs to Object. Basically, when you print out a class and you don't have the toString() method, it just prints out random stuff that is only a tiny bit understandable. For example:

class A {
    int data;
}

And in the main method:

A a = new A();
a.data = 4;
System.out.println(a);

You will get some weird text. However, after overriding the toString() method:

class A {
    int data;

    @Override
    public String toString() {
        return String.valueOf(data);
    }
}

Printing an instance of A will call the toString() method, so whatever String is returned will be printed. With the same code as before:

A a = new A();
a.data = 4;
System.out.println(a);

It will print 4 this time. For your custom LinkedList, override the toString() method for every a object, and it will print fine.

Higigig
  • 1,175
  • 1
  • 13
  • 25