Java:实现可比较但条件 if 太多。我怎样才能避免它们?
我有一个实现Comparable
的对象列表
。
我想对此列表进行排序,这就是我使用 Comparable
的原因。
每个对象都有一个字段 weight
,它由另外 3 个成员 int 变量组成。
对于具有最大权重
的对象,compareTo
返回1
。
最重要的不仅是 if ,
weightObj1.member1 > weightObj2.member1
weightObj1.member2 > weightObj2.member2
weightObj1.member3 > weightObj2.member3
而且实际上有点复杂,我最终得到的代码有太多条件 if 。
如果weightObj1.member1> WeightObj2.member1 成立,那么我关心是否 weightObj1.member2 > WeightObj2.member2。
反之亦然。
否则如果 weightObj1.member2 > WeightObj2.member2 成立,那么我关心是否
weightObj1.member3 > WeightObj2.member3
反之亦然。
最后如果weightObj1.member3> WeightObj2.member3 保持 AND 如果满足特定条件,则此 weightObj1
获胜,反之亦然
我想知道是否有类似这样的设计方法?
I have a list
of objects which implement Comparable
.
I want to sort this list and that is why I used the Comparable
.
Each object has a field, weight
that is composed of 3 other member int variables.
The compareTo
returns 1
for the object with the most weight
.
The most weight is not only if the
weightObj1.member1 > weightObj2.member1
weightObj1.member2 > weightObj2.member2
weightObj1.member3 > weightObj2.member3
but actually is a little more complicated and I end up with code with too many conditional ifs.
If the weightObj1.member1 > weightObj2.member1
holds then I care if weightObj1.member2 > weightObj2.member2
.
and vice versa.
else if weightObj1.member2 > weightObj2.member2
holds then I care if weightObj1.member3 > weightObj2.member3
and vice versa.
Finally if weightObj1.member3 > weightObj2.member3
holds AND if a specific condition is met then this weightObj1
wins and vice versa
I was wondering is there a design approach for something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试使用 Apache
commons-lang
< 中的CompareToBuilder
/a>:另请参阅
You can try with
CompareToBuilder
from Apachecommons-lang
:See also
与上述 Apache CompareToBuilder 类似,但包括泛型支持,Guava 提供 ComparisonChain:
Similar to the above-mentioned Apache CompareToBuilder, but including generics support, Guava provides ComparisonChain:
用于
Comparable
的 API 指出:由于感兴趣的值是 int 值,因此您应该能够得出一个值来捕获比较两个对象所需的所有比较和其他转换。当任何成员值发生更改时,只需更新单个值即可。
The API for
Comparable
states:Since the values of interest are
int
values you should be able to come up with a single value that captures all comparisons and other transformations you need to compare two of your objects. Just update the single value when any of the member values change.您可以尝试使用反射,迭代属性并比较它们。
You can try using reflection, iterate over properties and compare them.
你可以尝试这样的事情:
因为可比较不仅仅返回-1、0或1。它可以返回任何整数值,并且只考虑符号。
You can try something like this:
because comparable shall not just return -1, 0 or 1. It can return any integer value and only the sign is considered.