简体   繁体   中英

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. 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.

hashCode and equals methods:

   @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. This would be the class Participant in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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