hashMap - hashCode & equals 方法返回类型



我正在Java上玩纸牌游戏,我正在尝试比较hashMap到ArrayList中的元素的键(两者都是对象)。hashCode()和equals()被覆盖,但出现错误,我不确定它的哪一部分是错误的。

Cards类

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;
}
}

和我们要做的比较

/**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)); 
}
}

错误:点击查看错误图片

您正在尝试使用两个String对象作为布尔对象:

替换退货套装&&脸;在你的equals方法中使用return suitEquals &&faceEquals .

最新更新