为什么即使在放入正确的键值后,我的HashMap.get仍返回null值?

时间:2016-07-23 19:40:44

标签: java hashmap

我正在尝试从哈希映射中检索一些值,然后返回我正在检查键是否存在于映射中的值,并且此检查始终失败,从而导致空值。我已经覆盖了哈希码和等于方法。有人能告诉我这里我做错了吗?

类字段:

 private static final List<String> DZ=new ArrayList<String>();
 private static final Map<Participant,List<String>> subDz=new HashMap<Participant,List<String>>();

我要放入地图的方法:

    public static synchronized void handleSubs(String[] subData,String    dz){
    int[] lowdims=new int[subData.length];
    int[] highdims=new int[subData.length];
    try {
        for (int i=1;i<subData.length;i++){
            if (!subData[i].equals("") && !subData[i].equals("\n")){
                if (i%2==0){
                    highdims[i]=Integer.parseInt(subData[i].trim());
                }
                else {
                    lowdims[i]=Integer.parseInt(subData[i].trim());
                }
            }
        }
        if (!DZ.isEmpty()){
            DZ.clear();
        }
        DZ.add(dz);
        allSubDZs.add(dz);
        int[] newlow=removeZeroes(lowdims);
        int[] newhigh=removeZeroes(highdims);
        allSubs.add(new Participant(newlow,newhigh));
        subDz.put(new Participant(newlow,newhigh),DZ );
    }

我正在检索值的方法:

   public static List<String> getSubDz(Participant sub){
    if (subDz.containsKey(sub)){
        return subDz.get(sub);
    }
    else{
        logger.info("Subscription DZ not available");
        return null;
    }
}

getSubDz中的if检查总是失败,即使我把密钥放入其中。

hashCode和equals方法:

   @Override
   public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((DZ == null) ? 0 : DZ.hashCode());
    return result;
}
   @Override
   public boolean equals(final Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (this.getClass() != obj.getClass()) {
        return false;
    }
    final SubscriptionHandler other=(SubscriptionHandler)obj;
    if (DZ == null) {
        if (other.DZ != null) {
            return false;
        }
    } else if (!DZ.equals(other.DZ)) {
        return false;
    }
    return true;

1 个答案:

答案 0 :(得分:1)

您需要在密钥类上使用equals和hashcode。这将是您案件中的班级参与者。

相关问题