簡體   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