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");
}
[HashMap(Java)给出错误结果的可能的重复](http://stackoverflow.com/questions/9141557/hashmap-java-giving-wrong-results) – 2012-02-06 07:46:08