3 回答
TA贡献1906条经验 获得超10个赞
在你的情况下,你有List
接口和ArrayList
实现,你List
在地图的声明中正确使用了类型,但是你传递到ArrayList
在循环中声明一个 implementationaion( )。
问题出现是因为以下语句:
Map<Integer, List<String>> data = new HashMap<>();
空菱形符号为List<String>
. 它可以是 ArrayList、LinkedList 等。所以你不能确定编译器会使用ArrayList
实现。
为了支持代码可扩展性,建议进行所谓的针对接口的编程。只要可以避免将代码耦合到特定的实现,维护最通用的类型总是好的,也就是说,当您需要对其执行一些具体操作时,您将指定实现。
TA贡献1802条经验 获得超5个赞
因为你已经宣布在价值型Hashmap
的List<String>
,你给ArrayList<String>
的值类型 Map.Entry
中for loop
。
更改 Map<Integer, List<String>> data = new HashMap<>();
为 Map<Integer, ArrayList<String>> data = new HashMap<>();
TA贡献1854条经验 获得超8个赞
试试下面的代码:
for (Map.Entry<Integer, List<String>> entry : data.entrySet()) {
Integer key = entry.getKey();
List<String> value = entry.getValue();
for(String aString : value){
System.out.println("key : " + key + " value : " + aString);
}
添加回答
举报