Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have a cast in a compareTo(Object)

public int compareTo(Object x) {
    Task other = (Task)x;

    if (other.priority == this.priority) {
        System.out.println("Each task has the same priority level.");
        return 0;
    } else if (other.priority > this.priority) {
        System.out.println(other.priority + "\n" + this.priority);
        return -1;
    } else {
        System.out.println(this.priority + "\n" + other.priority);
        return 1;
    }
}

That's the code I have for a programming assignment for class. I'm not sure why I use Task other = (Task)x; or what it's doing here. The rest I understand. If anyone has a quick explanation of what that's actually doing here I would be greatful. Thank you!

like image 292
Sarah Diri Avatar asked Sep 27 '22 00:09

Sarah Diri


1 Answers

You are casting Object x to Task other - Object and Task are different types, so you need the cast so you can treat x as the expected type (and get to it's fields).

Normally in compareTo() you would first have something like if (x instanceof Task) before blindly casting it - if you don't and the types are different then things will crash)

like image 163
John3136 Avatar answered Oct 12 '22 22:10

John3136