繁体   English   中英

为什么即使放置正确的键值后,我的HashMap.get也返回空值?

[英]Why does my HashMap.get returns null value even after putting proper key,value?

我试图从哈希映射中检索一些值,然后返回值,然后检查键是否存在于映射中,并且此检查始终失败,这将导致空值。 我已经覆盖了哈希码和equals方法。 有人可以告诉我我在做什么错吗?

类字段:

 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;

您需要在键类上使用equals和hashcode。 在您的情况下,这将是全班参加者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM