0

Basically, i'm creating appointments, i'm trying to sort those appointments by date and time in chronological order.

Here's the compareTo method in my date class

    public int compareTo(Date obj) {

        Date d = (Date) obj;
        if(d == null) {
            return 1;
        }else if(this.year == d.year){
            return month.compareTo(d.month);
        }else if(this.month == d.month) {
            return day.compareTo(d.day);
    }else{
        return year.compareTo(d.year);
    }
 }

Here is the compareTo menthod in my time class

 public int compareTo(Time obj) {


            Time t = (Time) obj;
            if(t == null) {
                return 1;
            }else if(this.hour == t.hour){
                return minute.compareTo(t.minute);
            }else {
                return hour.compareTo(t.hour);
            }
    }

Now in my appointment class here's the compareTo method

public int compareTo(Appointment obj) {
        Appointment a = (Appointment) obj;
        if(a == null){
            return 1;
        }else if(this.date == a.date){
            return time.compareTo(a.time);
        } else{
            return date.compareTo(a.date);
        }
    }

I really can't understand why it's sorting by date but it won't sort by time when the date is the same.

Mr.Flawed
  • 39
  • 2
  • 2
    `this.date == a.date` should be `this.date.equals(a.date)` – Eran Oct 26 '17 at 09:44
  • 1
    Or `this.date.compareTo(a.date) == 0` . – Arnaud Oct 26 '17 at 09:46
  • 2
    Firstly, you don't need to cast as you're passing parameters of the proper type. Secondly, you want to use Java's own date/time objects (`Calendar`s up to Java 7, a `LocalDateTime` or better, a `ZonedDateTime` in Java 8). – Mena Oct 26 '17 at 10:12
  • Use java.time: `java.time.Instant::compareTo`. I Or, of booking appointments months out in future: `LocalDateTime::compareTo`. – Basil Bourque Oct 26 '17 at 13:32

0 Answers0