I am making a card game where the cards are represented as JLabels, having names and some other attributes which are changed during the game. I want to define equality as simply comparing the full names (represented by a field fullName) of two cards. However, this gives me the problem that I can't add the same card twice (because I have other fields in the Card class which might differ).
Apparently the JPanel does some checking about equals in the background. I then add a unique id field to each card and in the class i keep track of how many cards of a kind I created with
private static Map<AbstractCard, Integer> idCount = new HashMap<AbstractCard, Integer>();
and then each time the constructor of a certain card is invoked I increase the value in idCount. But then, if I add the check for id as well as the original name, not only the Map will break but it still doesn't add more than one card if the names are equal. This is what the method looks like now:
/**
* Compares this card to the specified object. The result is true if and only if
* the argument is not null and is a Card object that represents the same full name
* as this card.
* @return true if the cards are equal, otherwise false
*/
@Override
public boolean equals(Object o)
{
if (!(o instanceof AbstractCard))
return false;
else
{
AbstractCard c = (AbstractCard)o;
return this.fullName.equals(c.fullName) && this.id == c.id;
}
}
Any thoughts on how to solve this?
EDIT: My hashCode returns fullName.hashCode() and in the current version I add id.