元素的比较

wuchangjian2021-11-16 17:44:32编程学习

1.基本类型的比较

直接用 > , < , == 进行比较

2.对象的比较

2.1  覆写基类的equal(只能比较相等与否)

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Card card = (Card) o;
        return rank == card.rank &&
                suit.equals(card.suit);
    }
public static void main(String[] args) {
        Card card1 = new Card(1,"红桃");
        Card card2 = new Card(1,"红桃");
        System.out.println(card1.equals(card2) );
    }

2.2   实现Comparble接口,重写comparTo方法

class Card implements Comparable<Card>{
    public int rank; // 数值
    public String suit; // 花色
    public Card(int rank, String suit) {
        this.rank = rank;
        this.suit = suit;
    }
 @Override
    public int compareTo(Card o) {
        return o.rank-this.rank;
    }
public static void main(String[] args) {
        Card card1 = new Card(10,"红桃");
        Card card2 = new Card(2,"红桃");
        System.out.println(card1.compareTo(card2));     
    }

2.3   实现Comparator接口,重写compare方法(比comparble灵活)


class RankComparator implements Comparator<Card> {
    @Override
    public int compare(Card o1, Card o2) {
        return o1.rank-o2.rank;
    }
}
class SuitComparator implements Comparator<Card> {
    @Override
    public int compare(Card o1, Card o2) {
        return o1.suit.compareTo(o2.suit);
    }
}
public static void main(String[] args) {
        Card card1 = new Card(10,"红桃");
        Card card2 = new Card(2,"红桃");
        RankComparator rankComparator = new RankComparator();
        System.out.println(rankComparator.compare(card1, card2));
    }

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。