【发布时间】:2015-10-10 22:37:24
【问题描述】:
我正在尝试创建自己的哈希码,但我收到了一个空指针错误。是因为我的对象 Suit 和 Face 都没有自己的哈希码吗?我一直在网上查找哈希码的示例,因为这是我第一次使用它们,我尝试结合我在网上看到的示例。
import java.util.HashMap;
enum Suit {Diamonds, Hearts, Spades, Clubs};
enum Face {
King, Queen, Jack, Ten, Nine, Eight, Seven,
Six, Five, Four, Three, Two, Ace, Joker
};
public class SuitAndFace {
Suit suit;
Face face;
SuitAndFace(Suit s, Face f){
suit = s;
face = f;
}
public String toString(){
if(!face.toString().equals("Joker"))
return face + " of " + suit;
else//joker has no suit
return face.toString();
}
@Override
public boolean equals(Object o){
System.out.println(" in equals");
if(o instanceof SuitAndFace){
SuitAndFace s = (SuitAndFace) o;
if(this.face.equals(s.face) && this.suit.equals(s.face))
return true;
}
return false;
}
@Override
public int hashCode() {
int hash = 3;
hash = 7 * hash + this.suit.hashCode();
hash = 7 * hash + this.face.hashCode();
return hash;
}
}
更新方法:
@Override
public boolean equals(Object o){
System.out.println(" in equals");
if(o instanceof SuitAndFace){
SuitAndFace s = (SuitAndFace) o;
if(face != null && suit != null && this.face.equals(s.face) && this.suit.equals(s.face))
return true;
}
System.out.println("no match!");
return false;
}
@Override
public int hashCode() {
int hash = 3;
if(suit != null && face != null){
hash = 7 * hash + this.suit.hashCode();
hash = 7 * hash + this.face.hashCode();
}
return hash;
}
【问题讨论】:
-
suit必须是null。我们需要看看你在哪里使用了构造函数。 -
我猜西装或脸可能是空的,导致空指针。本质上,所有对象都有一个 .hasCode ()
-
@PaulBoddington 这是我如何使用我的构造函数/对象 hashMap.get(new SuitAndFace(findSuit(suitBox.getSelectedItem().toString()), findFace(faceBox.getSelectedItem().toString() ))) 这几乎只是从现有来源创建值