这是我的代码,我想知道这是怎么可能的:
HashMap<Integer,String> hashmap = new HashMap();
hashmap.put(1,"milind");
hashmap.put(2,"nelay");
HashMap hash = new HashMap();
hash.put("piyush",1);
hashmap.putAll(hash);
for (Object name: hashmap.keySet()) {
Object key = name.toString();
Object value = hashmap.get(name);
System.out.println(key + " " + value);
}
这是输出:
1 milind
2 nelay
piyush 1
最佳答案
您的hashmap
实际上没有指定键/值的类型,因此两个键都可以接受对象类型(或子类型,包括整数、字符串等)和值(value)。
这是您的第一行:
HashMap hashmap = new HashMap();
如果将此行更改为:
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
并继续下一行:
HashMap hash = new HashMap();
hash.put("piyush", 1);
hashmap.putAll(hash);
那么它就无法编译。
关于java - HashMap<Integer,String> 它如何取值<String,Integer>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38047298/