2016-07-23 16 views
0

我試圖從哈希映射檢索一些值,然後返回值我檢查密鑰是否存在於映射中,並且此檢查總是失敗,結果爲空值。我已經重寫了hash Code和equals方法。有人能告訴我我在這裏做錯了嗎?爲什麼我的HashMap.get即使在輸入正確的鍵值後也返回空值?

類字段:

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總是失敗,即使我把鑰匙放在裏面。

和的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; 
+0

爲什麼一切都是靜態的? –

+0

添加一些項目後打印出整個hashmap會發生什麼? –

+1

'Equals'和'hashCode'只讀了一個'static'字段,這沒有多大意義。 參與者的'equals'和'hashCode'如何實現?你是用'Participant'或者'Participant'來調用'getSubDz'嗎? – garnulf

回答

1

您需要的關鍵類equals和hashCode。這將是您的案例中的班級參與者。

相關問題