2012-02-04 60 views
0

我已經創建了一個散列映射,其中每個條目對應於3個值 密鑰對象值(其在數量上是兩個)HashMap的代碼不給所期望的結果

我已經創建了一個類,其對象創建和將結果存儲在散列圖中。 這是我在下面的代碼,我將我的傳入數據與哈希映射中的先前值進行比較。如果出現相同的數據,那麼我只是遞增該數據的計數器。問題是它多次打印出相同的數據。這是爲什麼?

class Info { 
    int counter; 
    String Data; 
} 
Info info = new Info(); 

int i=0; 
int lines=0; 

HashMap<String, Info> hMap = new HashMap<String, Info>(); 

try { 
    BufferedReader reader = 
        new BufferedReader(new FileReader("E:\\write1.txt")); 
    String line = null; 
    while ((line = reader.readLine()) != null) 
    { 
     lines++; 
     if(line.startsWith("Data:")) 
     { 
      String comingdata = line.replaceAll("Data:",""); 
      if(hMap.isEmpty()) // first time to put data in hashmap 
      { 
       info.counter=1; 
       info.Data=comingdata; 
       hMap.put("1",info); 
      } 
      else 
      { 
       int m=0; 
       // everytime it will run to 
       // check to increment the counter if the value already exists 
       for(i=1;i<=hMap.size();i++) 
       { 
        String skey = Integer.toString(i); 

        if(hMap.get(skey).Data.equals(comingdata)) 
        { 
         hMap.get(skey).counter= hMap.get(skey).counter+1; 
         m=2; 
        } 
       } 
       // making new entry in hashmap 
       if(m==0) 
       {         
        String skey = Integer.toString(hMap.size()+1); 
        info.counter=1; 
        info.Data=comingdata; 
        hMap.put(skey,info); 
       } 
      }// else end 
     } //if end 
    } //while end 
} //try end 
catch (Exception e) { } 
for(i=1;i<=hMap.size();i++) 
{ 
    String skey= Integer.toString(i); 
    System.out.println(hMap.get(skey).Data); 
    System.out.println(hMap.get(skey).counter); 
    System.out.println("\n"); 
} 
+0

[HashMap(Java)給出錯誤結果的可能的重複](http://stackoverflow.com/questions/9141557/hashmap-java-giving-wrong-results) – 2012-02-06 07:46:08

回答

2

你永遠只能創建一個對象Info,所以在HashMap映射到同一個對象所有鍵。在地圖中插入任何東西時,應該創建一個新的Info對象。

+1

非常感謝。我的問題現在已經解決了。 – Natasha 2012-02-04 15:24:05