我正在尝试将每个字符(以int形式)及其计数放入Hashmap中。 但是,当我打印出地图时,值始终为null。 谁能帮我弄清楚我的代码出了什么问题?
public class CharCounter implements IHuffConstants, ICharCounter {
private static Map<Integer, Integer> table;
CharCounter(){
table = new HashMap<Integer, Integer>();
}
/**
* Initialize state by counting bits/chunks in a stream
* @param stream is source of data
* @return count of all chunks/read
* @throws IOException if reading fails
*/
@Override
public int countAll(InputStream stream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
byte[] result = buffer.toByteArray();
for(int i =0 ; i<result.length;i++) {
table.put((int)result[i],table.getOrDefault(result[i],0)+1);
System.out.println(result[i] +","+table.get(result[i]));
}
return result.length;
}
输出: (测试“测试”一词)
116,null
101,null
115,null
116,null
115,null
116,null
114,null
105,null
110,null
103,null