简体   繁体   English

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

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

I am trying to retrieve some values from a Hash Map, before returning the value I am checking if the key is present in the map or not, and this check always fails which results in null value. 我试图从哈希映射中检索一些值,然后返回值,然后检查键是否存在于映射中,并且此检查始终失败,这将导致空值。 I have overridden hash Code and equals method as well. 我已经覆盖了哈希码和equals方法。 Could someone tell me what I am doing wrong here? 有人可以告诉我我在做什么错吗?

class fields: 类字段:

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

Method where I am putting into the map: 我在地图上放置的方法:

    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 );
    }

Method where I am retrieving the values: 我在其中检索值的方法:

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

The if check in the getSubDz always fails, even though I put the key in it. 即使我将密钥放入getSubDz中,if检查也总是失败。

hashCode and equals methods: 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;

You need equals and hashcode on the key class. 您需要在键类上使用equals和hashcode。 This would be the class Participant in your case. 在您的情况下,这将是全班参加者。

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

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