我编写了以下代码和输出,我希望是'Hello World'
我得到了null,有人可以解释这种行为.
import java.util.*;
public class Test {
static HashMap<Integer,String> hm = new HashMap<Integer, String>();
public static void main(String args[]) {
byte b = 1;
hm.put(1, "Hello World");
String s = hm.get(b);
System.out.println("The result is: " + s);
}
}
Run Code Online (Sandbox Code Playgroud)
您无法对Integer执行自动装箱操作.
这种混淆来自Map的get方法将key作为Object,而不是地图键类型中指定的Integer.所以你可以这样做:
String s = hm.get("hello");
Run Code Online (Sandbox Code Playgroud)
当然没有任何意义,但不会有编译错误.
要修复你应该手动将字节转换为整数(或int):
String s = hm.get((int)b);
Run Code Online (Sandbox Code Playgroud)