Java HashMap为某些键返回空值。有时
我创建了一个hashmap,其中包含一个字符串作为键,一个对象作为值。但是,当我尝试检索某些值时,得到的结果为空Java HashMap为某些键返回空值。有时,java,hashmap,Java,Hashmap,我创建了一个hashmap,其中包含一个字符串作为键,一个对象作为值。但是,当我尝试检索某些值时,得到的结果为空 // This returns all the keys and their values. for (String key : DevicesUsed.devicesUsedMap.keySet()) { if(DevicesUsed.devicesUsedMap.containsKey(key)) { System.out.prin
// This returns all the keys and their values.
for (String key : DevicesUsed.devicesUsedMap.keySet()) {
if(DevicesUsed.devicesUsedMap.containsKey(key)) {
System.out.println(key + " exists");
System.out.println(key + "\t" + DevicesUsed.devicesUsedMap.get(key));
} else {
System.out.println("Key does not exist.");
}
}
// This only works for some of the keys, that worked in the above code.
System.out.println(DevicesUsed.devicesUsedMap.get("WHITEALL")); // Works.
System.out.println(DevicesUsed.devicesUsedMap.get("REDCOVE")); // Returns null.
对于为什么某些键存在于一个块中而不存在于另一个块中,我感到非常困惑。在屏幕截图消息“WHITEALL-exist”中包含一个空格,但“REDCOVE-exist”包含两个空格
看起来您的键是“REDCOVE”,而不是“REDCOVE”。从您的屏幕截图中可以看出,REDCOVE的末尾肯定有一个空格。尝试使用System.out.PrintLDevicesUsed.devicesUsedMap.getREDCOVE 你昨天或今天早上没有问过同样的问题吗?当你用调试器运行这个程序时,你得到了什么信息?您是否创建了一个测试程序,一个尝试隔离错误的测试程序?如果是,请邮寄。如果不是,请考虑制作。@ J-Alx键看起来像一个字符串,所以不应该是。YUP,看起来所有的键都是8个字符串,右边是空格。我在创建密钥时忘记忘记尾随空间。它们是从字节数组中读取的。现在它似乎起作用了。