1.下列代码的运行结果是? HashMap map = new HashMap(); map.put(“name”,null); map.put(“name”,”xiyangyang”); System.out.println(map.get(“name”));
时间: 2023-05-18 12:05:24 浏览: 90
运行结果是 "xiyangyang"。
HashMap 允许 key 为 null,所以第一次 put 操作将 null 作为 key 存入 map 中。第二次 put 操作将 "name" 作为 key 存入 map 中,对应的 value 为 "xiyangyang"。由于 key 不能重复,第二次 put 操作会覆盖第一次的操作。最后,get 方法根据 key "name" 获取对应的 value,即 "xiyangyang"。
相关问题
java.util.HashMap map = new java.util.HashMap(); map.put("name", null); map.put("name", "Jack"); System.out.println(map.get("name"));
在这段代码中,首先创建了一个 `java.util.HashMap` 对象 `map`。然后,使用 `put` 方法向 `map` 中添加键值对。第一个 `put` 操作将键 `"name"` 对应的值设为 `null`,第二个 `put` 操作将键 `"name"` 对应的值更新为 `"Jack"`。
最后,使用 `get` 方法从 `map` 中获取键 `"name"` 对应的值,并将其打印输出。由于第二个 `put` 操作将键 `"name"` 对应的值更新为 `"Jack"`,因此最终打印输出的结果是 `"Jack"`。
优化这段代码:private List<DynamicSource> getDynamicSourceList(List<DasymesQltyMpCertfInfoItemMod> itemModList) { List<Map<String, String>> mapList = new ArrayList<>(); if (itemModList == null || itemModList.size() == 0) { Map<String, String> map = new HashMap<>(); map.put("no", null); map.put("name", null); map.put("portion", null); mapList.add(map); return DynamicSource.createList("detail", mapList); } for (int i = 1; i <= itemModList.size(); i++) { DasymesQltyMpCertfInfoItemMod item = itemModList.get(i - 1); Map<String, String> map = new HashMap<>(); map.put("no", i + ""); map.put("name", item.getItemName()); map.put("portion", item.getPortion()); mapList.add(map); } return DynamicSource.createList("detail", mapList); }
可以优化的地方如下:
1. 在if语句中,可以直接创建map并添加到mapList中,避免了在后面的循环中再创建map。
2. 在循环中,可以使用foreach循环代替for循环,避免了使用i变量。
3. 在创建DynamicSource时,可以直接使用mapList,不需要再创建一个中间变量。
优化后的代码如下:
```
private List<DynamicSource> getDynamicSourceList(List<DasymesQltyMpCertfInfoItemMod> itemModList) {
List<Map<String, String>> mapList = new ArrayList<>();
if (itemModList == null || itemModList.isEmpty()) {
mapList.add(Map.of(
"no", null,
"name", null,
"portion", null
));
} else {
for (DasymesQltyMpCertfInfoItemMod item : itemModList) {
Map<String, String> map = new HashMap<>();
map.put("no", String.valueOf(mapList.size() + 1));
map.put("name", item.getItemName());
map.put("portion", item.getPortion());
mapList.add(map);
}
}
return DynamicSource.createList("detail", mapList);
}
```
这样代码更加简洁易读,也更加高效。
阅读全文
相关推荐













