Suggestions for a hashcode of a Card object in a poker game?
How is the hashcode compu开发者_开发问答ted for a card object which consists of enum suit and enum rank ?
If you're using Eclipse, it can generate a "good enough" hashCode()
implementation for you:
public class Card
{
private Suit suit;
private Rank rank;
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((rank == null) ? 0 : rank.hashCode());
result = prime * result + ((suit == null) ? 0 : suit.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (!(obj instanceof Card)) return false;
Card other = (Card) obj;
if (rank != other.rank) return false;
if (suit != other.suit) return false;
return true;
}
}
I can only imagine that NetBeans, IntelliJ IDEA, etc., can do this as well.
That said, since the domain is small, this implementation will work equally well (I think...):
public int hashCode()
{
int rankHash = ((rank == null) ? 0 : (1+rank.ordinal()));
int suitHash = ((suit == null) ? 0 : (1+suit.ordinal()));
return rankHash + 31*suitHash;
}
This assumes that Rank
ordinals are 0-12
inclusive and Suit
ordinals are 0-3
inclusive. Note that most of the ugliness there comes from the null checks. If the values can never be null, then:
public int hashCode()
{
return rank.ordinal() + 31*suit.ordinal();
}
With so little value space (is it 13 times 4?) it makes no sense to assign any two cards the same hash-code. So it's completely up to you, but something like:
A spades = 1
K spades = 2
....
A clubs = 21
K clubs = 22
....
should be OK.
Generally it makes sense to define a hashcode if there are really huge numbers of possible values (like every possible String
value or every possible list of numbers List<Number>
) and to have them limited to (projected into) a limited space of hashcode values. If we are talking about hashCode()
as defined by java.lang.Object
API then the 'limited space of hashcode values' has to fit into int
type (integers).
The space of the cards domain ( 52 ) is small enough to fit into an enum
it self. And that would give you a natural primary key for identification as well, since hashCode
should be a unique identifier for the internal state of the object as well.
Here is some pseudo Java code to give you an idea:
public enum Suit
HEART, CLUB, SPADE, DIAMOND
public enum Rank
TWO, THREE, FOUR ... KING, QUEEN, ACE
public enum Card
private final Suit suit;
private final Rank rank;
private Card(final Suit s, final Rank r);
ACE_HEARTS(ACE,HEART), TWO_HEARTS(TWO,HEART), ... KING_DIAMONDS(KING, DIAMOND);
public int hashCode() { return this.ordinal; )
精彩评论