简体   繁体   English

可比性是将事物按降序而不是升序排列

[英]comparable is putting things in descending order instead of ascending

So, this is likely just a logic bug on my part but I'm not sure how. 因此,这可能只是我的逻辑错误,但我不确定如何解决。

@Override
public int compareTo( Activity t ) {
    // currently we're naturally sorting by created, description, uuid
    int createdComp = t.created.compareTo( created ); // created is an Instant

    if ( createdComp == 0 ) {
        int descComp = t.description.compareTo( description ); // description is a String
        if ( descComp == 0 ) {
            return t.id.compareTo( id ); // id is a UUID
        } else {
            return descComp;
        }

    }
    return createdComp;
}

here's my debugging code, for the code I haven't put, it uses the same Instant, and the UUID's are being randomly generated. 这是我的调试代码,对于我尚未放入的代码,它使用相同的Instant,并且UUID随机生成。

    NavigableSet<Activity> ai = new TreeSet( Arrays.asList( i, g, h, f, a, b, c, e, d ) );

    assertEquals( ai.size(), 9, "NaviSet Size is 9" );

    for ( Activity act : ai ) {
        System.out.println( act );
    }

Here's the output 这是输出

1a8861eb-96c8-44ef-a9a5-ffbbeaf6b09e I 2014-02-01T16:00:42.102Z
3703a83c-04b4-4ed1-bdc6-b1da083900ea H 2014-02-01T16:00:42.102Z
1e68df32-18a5-4ce1-bb12-41dd3be97e3c G 2014-02-01T16:00:42.102Z
d73b0e03-fd01-4a70-a20f-500e2cf0b3dd F 2014-02-01T16:00:42.102Z
4aba5877-ed0e-4457-800c-522e3a2b72a3 E 2014-02-01T16:00:42.102Z
a90c7dae-ef9f-453b-9416-b7916ace4b5f D 2014-02-01T16:00:42.102Z
fdbfbb6b-d39b-4f15-a309-d105f0caa7a5 C 2014-02-01T16:00:42.101Z
2ed80ac0-768e-40c3-b03a-11b417e2893f B 2014-02-01T16:00:42.101Z
ef8b27db-6102-4ca5-8803-b63bea405be3 A 2014-02-01T16:00:42.098Z

Why are they in descending order? 为什么它们按降序排列? and how can I fix my code so that they're in ascending order by default? 以及如何解决我的代码,以便默认情况下它们按升序排列? (obviously navigable set has asc/desc operations) (显然,可导航的集合具有asc / desc操作)

Your logic is inverted in all your comparisons. 您的逻辑在所有比较中都是相反的。
The logic should always be "this compared to that". 逻辑应该始终是“与此相比”。

For example, change this line of your code: 例如,更改代码的这一行:

int createdComp = t.created.compareTo( created );

To: 至:

int createdComp = created.compareTo(t.created);

It's the way compare to works. 这是与作品进行比较的方式。

You should compare the object's value to the incoming value. 您应该将对象的值与传入的值进行比较。

If you do it the other way round, you end up with a reverse order. 如果以相反的方式进行操作,则最终将得到相反的顺序。

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

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