Why in the application 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; } } 

This is the programming code for the class. I am not sure why I am using Task other = (Task)x; or what is he doing here. I understand the rest. If anyone has a quick explanation of what they are actually doing here, I would be generous. Thanks!

+5
source share
2 answers

You drop Object x into Task other - Object and Task different types, so you need to throw so that you can treat x as the expected type (and get its fields).

Usually in compareTo() you first have something like if (x instanceof Task) before you blindly pour it - if you don't, and the types will be different, then everything will fail)

+2
source

The method signature accepts an object of type Object , therefore, in order to refer to the priority variable inside the passed object, it must cast the Task object, since the variable exists only in the Task class.

Personally, I think this was bad practice, since you don’t know which object is being passed (any class of subclasses of the Object class can be passed), so the validation instance will not go the way you want to throw a ClassCastException runtime error.

Alternatively, you can use generics to indicate which object you want to compare to. Therefore, instead ...

 public class Task implements Comparable { private int priority = 1; @Override public int compareTo(Object o) { if (o instanceof Task) { Task t = (Task) o; return this.priority < t.priority; } return -1; } } 

... you could do it ...

 public class Task implements Comparable<Task> { private int priority = 1; @Override public int compareTo(Task t) { return this.priority < t.priority; } } 
+2
source

Source: https://habr.com/ru/post/1237695/


All Articles