简体   繁体   English

比较Java中对象的更优雅方法

[英]More elegant way of comparing objects in Java

Java has an inteface Comparator<T> , that has a method int compare(T o1, T o2) . Java有一个接口Comparator<T> ,它具有方法int compare(T o1, T o2)

EDIT: 编辑:

I was wrong with this: 我错了:

The returned integer must be -1 if the first object is less than second one, 1 if second one is less than first one, 0 if they're equal. 返回的整数必须-1如果第一对象是小于第二个, 1如果第二个是小于第一个, 0如果他们相等。

Docs state: 文件状态:

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 作为第一个参数小于,等于或大于第二个参数的负整数,零或正整数。

So I rephrase my question: Is there a more elegant way of comparing objects, than bearing in mind that comparator.compare(o1, o2) < 0 actually means that first object is less than second one? 所以我重新表述我的问题:是否有一种比较对象的优雅方法,而不是牢牢记住comparator.compare(o1, o2) < 0实际上意味着第一个对象小于第二个对象?

Compare your statement 比较你的陈述

The returned integer must be -1 if the first object is less than second one, 1 if second one is less than first one, 0 if they're equal. 如果第一个对象小于第二个对象,则返回的整数必须为-1;如果第二个对象小于第一个对象,则返回的整数必须为1;如果相等,则返回0。

with the official statement 与官方声明

Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 当第一个参数小于,等于或大于第二个参数时,返回负整数,零或正整数。

and note that the only appropriate constant is zero. 并注意唯一合适的常数为零。

The official interface contract for compare method is: 比较方法的官方接口约定为:

Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 当第一个参数小于,等于或大于第二个参数时,返回负整数,零或正整数。

While in fact all you need is three values, this logic can be used to write elegant code like this: 尽管实际上您只需要三个值,但是可以使用此逻辑编写优雅的代码,如下所示:

public int compare(MyObject o1, MyObject o2){
    return o1.getIntValue() - o2.getIntValue();
}

Which in one line not only gives you which object is greater (or equal), it even gives you how much one is greater than the other. 在哪一行中,哪一个不仅给您提供哪个对象更大(或相等),甚至还给您一个对象大于另一个对象的数量。

(Integer overflows not considered.) (不考虑整数溢出。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM