0
嗨,夥計們我正在學習或試圖學習如何使用compareTo()..我有一個簡單的類實現它,但在相反的順序,我想有人可以請指出明顯對我來說,因爲我似乎一直想念它。我如何反轉這一點。 這是我的簡單例子。學習使用compareTo
import java.util.*;
public class H283
{
public static void main(String args[])
{
Task[] tasks = new Task[4];
tasks[0] = new Task("Homework");
tasks[0].setPriority(7);
tasks[1] = new Task("Eat lunch");
tasks[1].setPriority(Priority.MIN_PRIORITY);
tasks[2] = new Task("Attend class");
tasks[2].setPriority(Priority.MAX_PRIORITY);
tasks[3] = new Task("Ned's project");
tasks[3].setPriority(4);
Arrays.sort(tasks);
System.out.println("\n TO-DO\n---------");
for (int i = 0; i < tasks.length; i++)
System.out.println(tasks[i].getName() + " \tpriority: " + tasks[i].getPriority());
}
}
interface Priority
{
static final int MED_PRIORITY = 5;
static final int MAX_PRIORITY = 10;
static final int MIN_PRIORITY = 1;
//-----------------------------------------------------------------
// Sets the object's priority level.
//-----------------------------------------------------------------
public void setPriority (int value);
//-----------------------------------------------------------------
// Returns the object's priority level.
//-----------------------------------------------------------------
public int getPriority();
}
class Task implements Priority, Comparable<Task>
{
String name;
private int priority;
//-----------------------------------------------------------------
// Sets up this task with a medium priority level.
//-----------------------------------------------------------------
public Task (String taskName)
{
name = taskName;
priority = MED_PRIORITY;
}
//-----------------------------------------------------------------
// Returns this task's name.
//-----------------------------------------------------------------
String getName()
{
return name;
}
//-----------------------------------------------------------------
// Sets this task's priority level.
//-----------------------------------------------------------------
public void setPriority (int value)
{
priority = value;
}
//-----------------------------------------------------------------
// Returns this task's priority level.
//-----------------------------------------------------------------
public int getPriority()
{
return priority;
}
public int compareTo(Task other)
{
//here is where i'd like to reverse the order
int thePriority = getPriority()-other.getPriority();
if (thePriority != 0)
return thePriority;
else
return getPriority()-other.getPriority();
}
}
任何意見將是真棒......謝謝
顛倒什麼順序? – Luminous
您可以通過將'compareTo'減少爲單行來簡化和反轉順序:'return other.getPriority() - getPriority()' – neuronaut
謝謝..非常簡單的好建議。 – Brett