비교가능한카드

앞장에서 설명한 카드에, 비교가능한 기능을 탑재해보자

제네릭 프로그래밍의 한가지 방법으로, 커스텀한 자료에대해 비교기능을 탑재하여

여러가지 자료구조에서 추가적인 구현없이 비교가능해진다. 소팅이 한가지예이다. 

여기서 비교가능하다란 의미는 누가 더 중요하고 나쁘고가 아닌 비지니스 로직내에서 의미가 있다. 

  • 6Spade  > 6Heart  : 6Spade가 높은것은 정통 포커룰에는 없다. / 하지만 커스텀된 룰에서 승패가 결정되면 Spade가 더 중요한 요소이다.
  • 7Heart > 6 Heart : 7이 더 높다란것도 정통 포커룰에 없다.
  • 2,3,4,5, : 비교가능을 통해 소팅, 족보계산 편이를 위해 사용자 친화적인 소팅에서 의미가 있다.
public class Card implements Comparable<Card>
{
    @Override
    public int compareTo(Card other) {
        if (this.getValue()<other.getValue()) return -1;
        else if (this.getValue()>other.getValue()) return 1;
        else return 0;
    }

    @Override
    public boolean equals(Object o){
        Card anotherCard = (Card) o;
        return this.getValue() == anotherCard.getValue();
    }

    @Override
    public int hashCode(){
        assert false: "no hashcode implementation";
        return 17;
    }
    
}
  • No labels
Write a comment…