【问题标题】:Why am I getting a null pointer for my hashcode?为什么我的哈希码得到一个空指针?
【发布时间】: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() ))) 这几乎只是从现有来源创建值

标签: java hashmap hashcode


【解决方案1】:

我刚刚意识到您似乎将小丑代表为suit == nullface == Joker。如果卡片是小丑,则无论何时执行suit.anything,您都会得到NullPointerException

那行可能是:

hash = 7 * hash + this.suit == null ? 0 : this.suit.hashCode();

或者,您也可以将Joker 常量添加到Suit 枚举中,这样您就不必担心null

编辑

通过您编辑的代码,我可以看到这些行

if(face != null && suit != null && this.face.equals(s.face) && this.suit.equals(s.face))
        return true;

不太对。首先,您正在比较 suitface(显然是错字)。我也猜你希望小丑是平等的?目前它们不会是因为如果suit == null 方法返回false。线条应该很简单

if (face == s.face && suit == s.suit)
    return true;

您不需要将.equals 用于枚举常量。改用== 的好处在于,因为您没有使用方法,所以无需担心空值。

【讨论】:

  • 谢谢。我已经用你所说的更新了我的代码。但是我的equals由于某种原因不起作用,当项目确实存在时它返回false。
  • @mrnoobynoob 你能编辑问题吗?保留原始版本,以便 2 个答案有意义,但在下面添加新版本。
  • @mrnoobynoob 没问题。我很高兴能帮上忙。
猜你喜欢
  • 2011-12-13
  • 2011-04-14
  • 1970-01-01
  • 2019-07-25
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
相关资源
最近更新 更多