Natasha
Natasha

Reputation: 35

HashMap code not giving the desired results

I have created a hash map in which each entry corresponds to 3 values Key object values ( which are two in number)

I have created a class, whose object I create and store the results in a hash map. This is my code below in which I compare my incoming data with the previous values in the hash map. If the same data comes then I just increment the counter of that data. Problem is that it prints out the same data multiple times. Why is that?

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

Upvotes: 0

Views: 100

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183878

You only ever create one Info object, so all keys in the HashMap map to the same object. When you insert anything into the map, you should create a new Info object.

Upvotes: 2

Related Questions