在学map集合,遇到了问题,这两段代码为什么输出结果会不一样呢,get()方法后面的 “” “” 是有什么意义吗?
public class CollectionDemo10_4 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String,String>();
//创建map集合
map.put("1","apple");
map.put("2", "pear");
map.put("3", "orange");
//向集合中添加对象
for(int i = 1;i <= 3;i++) {
System.out.println("第" + i + "元素是:" + map.get("" + i + ""));
}
}
}
输出结果:
第1元素是:apple
第2元素是:pear
第3元素是:orange
public class CollectionDemo10_4 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String,String>();
//创建map集合
map.put("1","apple");
map.put("2", "pear");
map.put("3", "orange");
//向集合中添加对象
for(int i = 1;i <= 3;i++) {
System.out.println("第" + i + "元素是:" + map.get(i));
}
}
}
输出结果:
第1元素是:null
第2元素是:null
第3元素是:null
map.get("" + i + "") 将 i 转成字符串形式,因为你存进去的key是字符串格式.
map.get(i) 是 int ,所以获取不到
因为你第二种的get(Object key)这个参数在你的map中不存在,同一样1,但第二个是整型,但你存储的是字符串型,所以导致获取到的为null
因为你的map定义的泛型key为string类型
map.get(i) 这个i是int 所以查不到就是null