如何在Java中按对象属性排序arrayList <Object>

use*_*772 2 java sorting collections compare long-integer

我有类(JavaBean,如果你想这样称呼它)

class Tweet{

private millis; //number of millis since 1970
//other attributes and getters and setters, but i want to sort onlny by millis

public long getMillis() {
   return millis;
}

}
Run Code Online (Sandbox Code Playgroud)

比较器应该看起来像这样:

class TweetComparator implements Comparator {
     @Override
     public int  compare(Tweet t1, Tweet t2) {
     //something
     //this doesn't work
     //return t2.getMillis().compareTo(t1.getMillis());
     return ??;//what should be here?
     }

    }
Run Code Online (Sandbox Code Playgroud)

这将在程序中

List<Tweet> tweets = new ArrayList<Tweet>();
tweets.add(...); //just fill the list
//i need newest (with hightest millis value first) so I probably need to call reverse order
Collection.reverse(tweets)
Collection.sort(tweets, new TweetComparator());
Run Code Online (Sandbox Code Playgroud)

我在这里这里找到了一些参考.但我不知道如何完成我的代码.

Evg*_*eev 12

您的比较器应该与此类似

class TweetComparator implements Comparator<Tweet> {
    @Override
    public int compare(Tweet t1, Tweet t2) {
        return Long.compare(t1.getMillis(), t2.getMillis()); 
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这static int Long.compare是自Java 7以来