【Data Structures】 8. Sorting in Java—Comparable and Comparator

To sort an array or a collection of objects, we need to make sure that the objects are mutually comparable. 

This is supported by the Comparable interface that contains only one method:

compareTo(Object) : int

The return value of the compareTo() method is negative, zero or positive:

1. Negative when the current instance comes before the argument in the ordering.

2. Positive when the current instance comes after the argument.

3. Otherwises zero is the return value.


Keep in mind that the default equals() method compares two objects using their references (Identity comparison).

If x.equals(y) is true, then x.hashCode() must be same as y.hashCode().


Objects that implement the Comparable interface can be sorted by the sort() method of the Arrays or Collections classes


If you want to have a few different ways of comparing, pay attention to the fact that you need another class that implements the Comparator interface and compare() method takes two arguments!

import java.util.*;
public class CompareBySuitRank implements Comparator<Card> {
    @Override
    public int compare(Card x, Card y) {
        int suitResult = x.getSuit().compareTo(y.getSuit());
        if (suitResult != 0) {
            return suitResult;
        }
        return x.getRank() - y.getRank();
    }
}

List<Card> cards = new ArrayList<Card>();
cards.add(new Card("hearts", 2));
cards.add(new Card("diamonds", 2));
cards.add(new Card("spades", 3));
cards.add(new Card("clubs", 4));
cards.add(new Card("hearts", 1));

Collections.sort(cards, new CompareBySuitRank());
for (Card c : cards) {
    System.out.println(c);
}


Tip!

compareTo method defines the NATURAL ORDER of the type whereas compare method is used to define different custom orders of the type.




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值