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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With