我有类(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;
}
}
比较者应该看起来像这样:
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?
}
}
这将在程序中
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());
答案 0 :(得分:11)
您的比较器应该与此类似
class TweetComparator implements Comparator<Tweet> {
@Override
public int compare(Tweet t1, Tweet t2) {
return Long.compare(t1.getMillis(), t2.getMillis());
}
}
请注意,static int Long.compare
是自Java 7以来的
答案 1 :(得分:4)
比较方法返回: 第一个参数的负整数,零或正整数小于,等于,>>或大于第二个参数。
逻辑 -
if t1.millis > t2.millis
return -1;
else if t1.millis < t2.millis
return +1;
代码 -
class TweetComparator implements Comparator<Tweet> {
@Override
public int compare(Tweet t1, Tweet t2) {
if(s1.i>s2.i)
return -1;
else if(s1.i<s2.i)
return +1;
return 0;
}
}
答案 2 :(得分:3)
试试这个:
@Override
public int compare(Tweet t1, Tweet t2) {
return t1.getMillis().compareTo(t2.getMillis());
}
如果要使用Long类的内置compareTo方法,请将mills变为long。 否则在比较方法中,将您的millis与t1和t2进行比较,如下所示。
long t1Val = t1.getMillis();
long t2Val = t2.getMillis();
return (t1Val<t2Val? -1 : (t1Val ==t2Val? 0 : 1));
(直接来自原版Long课程)