android comparator,android - java comparator, how to sort by integer? - Stack Overflow

Simply changing

public int compare(Dog d, Dog d1) {

return d.age - d1.age;

}

to

public int compare(Dog d, Dog d1) {

return d1.age - d.age;

}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable {

private String name;

private int age;

public static final Comparator DESCENDING_COMPARATOR = new Comparator() {

// Overriding the compare method to sort the age

public int compare(Dog d, Dog d1) {

return d.age - d1.age;

}

};

Dog(String n, int a) {

name = n;

age = a;

}

public String getDogName() {

return name;

}

public int getDogAge() {

return age;

}

// Overriding the compareTo method

public int compareTo(Dog d) {

return (this.name).compareTo(d.name);

}

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator

Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2:

Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3:

With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator DESCENDING_COMPARATOR =

Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {

return DESCENDING_COMPARATOR.compare(d, d1);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值