-7

For example, I have two objects:

Icecream ice1 = new Icecream(vanilla, newDate(11, 09, 09));
Icecream ice2 = new Icecream(choko, newDate(10, 08, 08));
// where first argument is a String and second argument is a Date 

how can I print the out so that they will be ordered by the date starting from earliest? (toStrign method is already configured)

Output sholud be:

Vanilla, 10-08-08
Vanilla, 11-09-09

Thank you!

2

4 Answers 4

4

Implement your own comparator and call sort on the collection. Good tutorial is here for example:

Java Sorting: Comparator vs Comparable Tutorial

1
  • 1
    +1, for linking to a tutorial and not spoonfeeding the answer.
    – camickr
    Commented Dec 12, 2011 at 0:58
1

You can define a natural ordering for your class IceCream by implementing the Comparator interface.

public class IceCream implements Comparator{
    // ...
    final String name; 
    final Date date;
    public Icecream(String name, Date date){
       this.name = name;
       this.date = date;
    }
    public int compare(Object o1, Object o2) {
        return ((IceCream)o1).date.compareTo(((IceCream)o2).date);
    }
}
3
  • if it not difficult then please show how Commented Dec 11, 2011 at 21:26
  • I knew somebody would spoonfeed the answer! So much for learning search skills.
    – camickr
    Commented Dec 12, 2011 at 0:58
  • This answer is wrong: you want to implement the Comparable interface, not Comparator. And in either case, you should be using the parameterized type, not the raw type, so it should be public class IceCream implements Comparable<IceCream>. Commented Dec 12, 2011 at 19:10
1

Make a custom comparator for your Icecream class.

class DateComparator implements Comparator {

    public int compare(Object ic1, Object ic22){

        /*
         * parameter are of type Object, so we have to downcast it
         * to Icecream objects
         */

        Date ic1Date = ((Icecream)ic1).getDate();        
        Date ic2Date = ((Icecream)ic2).getDate();

        return ic1Date.compareTo(ic2Date);   
    }
}
1

I would make two classes, one that implements Comparator and one Sorter that handles the sorting of an array, with a comparator as parameter. Then put the ice creams in a array and call your sort method in Sorter.

Not the answer you're looking for? Browse other questions tagged or ask your own question.