A
char是16位无符号值,如果将其强制转换为
int,则将获得0到65535之间的值。这意味着您可以使用数组存储字符:
int[] charCounts = new int[65536];
然后当您想要记录发生的情况时
char c:
charCounts[(int) c]++;
当您要读取计数时:
for (int i=0; i<65536; i++) if (charCounts[i]>0) System.out.println((char)(i)+": "+charCounts[i]);
HashMap<Character,Integer>如果您想做一个练习,那么没有什么可以阻止您这样做的,尽管它比它需要的要重得多:
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
以及何时要记录以下事件的发生
char c:
if (!map.containsKey(c)) map.put(c,1);else map.put(c,map.get(c)+1);
以及当您想阅读时:
for (Map.Entry<Character,Integer> entry: map.entrySet()) System.out.println(entry.getKey()+": "+entry.getValue());
请注意,对于所有这些,我假设您只处理可打印字符。如果没有,您将在打印出来时对此做些事情。



