Map keySet() entrySet() 最终结果不一致

wd9053 2010-09-11 07:41:26
在做一道算法题,结果总是RuntimeError,一步步查后发现通过keySet()遍历与通过entrySet()遍历产生结果不同,前者产生RuntimeEror(第二个注释块),后者测试通过(第一个注释块)。
有点晕了,不知道是什么原因

import java.math.*;
import java.util.*;

public class Main
{
static int[] ten = {1, 10, 100, 1000, 10000, 100000, 1000000};

static char check(char c)
{
if(c <= '9' && c >= '0')
{
return c;
}
if(c < 'Q')
{
return (char)('2' + (c - 'A') / 3);
}
else
{
return (char)('7' + (c - 'Q') / 3);
}
}

static class Counter
{
public int value = 1;
}

public static void main(String[] args)
{
try
{
Scanner scan = new Scanner(System.in);
int total = scan.nextInt();
Map<String, Counter> map = new TreeMap<String, Counter>();

scan.nextLine();
char c;
for(int i = 0; i < total; i++)
{
String temp = scan.nextLine();
StringBuilder builder = new StringBuilder();
for(int j = 0, k = 0; j < temp.length(); j++)
{
if(temp.charAt(j) == '-')
{
continue;
}
c = check(temp.charAt(j));
builder.append(c);
}

String str = builder.toString();
Counter counter = (Counter)map.get(str);
if(counter == null)
{
counter = new Counter();
map.put(str, counter);
}
else
{
counter.value++;
}
}

boolean hasResult = false;

/* 去掉注释测试通过
for (Map.Entry entry : map.entrySet())
{
String str = entry.getKey().toString();
Counter counter = map.get(str);//(Counter)entry.getValue();结果均正确
if (counter.value > 1)
{
System.out.println(str.substring(0, 3) + "-" + str.substring(3) + " " + counter.value);
hasResult = true;
}
}*/

/* 去掉注释测试不通过 Runtime Error
for(String str : map.keySet())
{
Counter counter = map.get(str);
if(counter.value > 1)
{
System.out.println(str.substring(0, 3) + "-" + str.substring(3) + " " + counter.value);
hasResult = true;
}
}*/

if(!hasResult)
{
System.out.print("No duplicates.");
return;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
...全文
450 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wd9053 2010-09-11
  • 打赏
  • 举报
回复
无语了。。
之前明明是RE的,我又从网上拷了之前RE的代码,测试却通过了,估计是平台的事...
huntor 2010-09-11
  • 打赏
  • 举报
回复
我把注释块去掉后,没遇到你说的情况。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧