I'm working on a Card game on Java and I'm trying to compare the key from a hashMap to an element in an ArrayList (both are objects). hashCode() and equals() are overridden but an error showed up and I'm not sure which part of it is wrong.
Here's the Cards class
class Cards implements Comparable<Cards> {
public String suit;
public String face;
public Cards() {
}
//Create Cards object
public Cards (String suit, String face){
this.suit = suit;
this.face = face;
}
//Return card suit
public String getSuit() {
return suit;
}
//Return card face
public String getFace() {
return face;
}
@Override
public int compareTo(Cards currentCards) {
if (getSuit().compareTo(currentCards.getSuit()) > 0) {
return 1;
} else if ((getSuit().compareTo(currentCards.getSuit())) < 0){
return -1;
} else if ((getSuit().compareTo(currentCards.getSuit())) == 0){
if (getFace().compareTo(currentCards.getFace()) > 0){
return 1;
} else if (getFace().compareTo(currentCards.getFace()) < 0){
return -1;
}
}
return 0;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Cards))
return false;
Cards other = (Cards)o;
boolean suitEquals = (this.suit == null && other.suit == null) ||
(this.suit != null && this.suit.equals(other.suit));
boolean faceEquals = (this.face == null && other.face == null) ||
(this.face != null && this.face.equals(other.face));
return suit && face;
}
@Override
public int hashCode() {
int result = 17;
if (suit != null) {
result = 31 * result + suit.hashCode();
}
if (face != null) {
result = 31 * result + face.hashCode();
}
return result;
}
}
and the comparison we're trying to work
/**Creating Cards object*/
String[] SUIT = new String[]{ "d", "c", "h", "s" };
String[] FACE = new String[]{ null, "A", "2", "3", "4", "5", "6", "7", "8", "9", "X", "J", "Q", "K" };
Cards[] cardDeck = new Cards[52];
int index = 0;
for (int i = 0; i <= 3; i++) {
for (int j = 1; j <= 13; j++) {
cardDeck[index] = new Cards(SUIT[i], FACE[j]);
index++;
}
}
/**Player 1 in hand*/
ArrayList<Cards> player1 = new ArrayList<Cards>();
int j=0;
for (int i = 0; i <18; i++){
player1.add(i, cardDeck[j++]);
}
for(Cards n : player1){
if (Points.containsKey(n)){
System.out.println("Card points: " + Points.get(n));
}
}
You are trying to use two String objects as boolean objects:
Replace return suit && face; in your equals method with return suitEquals && faceEquals.