目前我正在编写一个针对二次函数的compareTo方法,其形式为:ax^2 + bx + c。
a、b、c是通过构造函数传递给类的整数系数。
在compareTo方法中,我应该首先比较两个函数之间的a系数,但如果它们相等,我会比较b系数。如果b相等,我会比较c。
我为此想出的方法变得非常丑陋:
public int compareTo(QuadraticFunction other)
{
if (a > other.a)
return 1;
else if (a < other.a)
return -1;
else if (b > other.b)
return 1;
else if (b < other.b)
return -1;
else if (c > other.c)
return 1;
else if (c < other.c)
return -1;
else
return 0;
}
我在想,如果你有这些“分层”比较系统(例如在比较a之前先比较b,在比较b之前先比较c),那么最好的实现方式是什么?如果有10多个变量需要进行比较,我无法想象编写类似于我的方法。