问题描述
我正在 Java 上开发纸牌游戏,我正在尝试将 hashMap 中的键与 ArrayList 中的元素进行比较(两者都是对象)。 hashCode() 和 equals() 被覆盖,但出现了一个错误,我不确定它的哪一部分是错误的。
这是卡片类
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));
}
}
错误: click to see picture of error
解决方法
您正在尝试使用两个 String 对象作为布尔对象:
换回西装&&脸;在你的equals方法中返回suitEquals && faceEquals。