例如,为了迭代List<串GT;和列表<列表与LT;串GT;>使用相同的功能,我可以这样写:
import java.util.*;
public class Test{
public static void print(Object obj) {
if(obj instanceof List){
List list=(List)obj;
System.out.print("[");
for(Object obj2 : list){
print(obj2);
}
System.out.print("]");
}else{
System.out.print(obj+",");
}
}
public static void main(String[] args){
String l0="a";
System.out.println(l0);
List<String> l1=Arrays.asList("a","b");
print(l1);
System.out.println("");
List<List<String> > l2=Arrays.asList(Arrays.asList("a","b"),Arrays.asList("c","d"));
print(l2);
}
}
输出:
a
[a b ]
[[a b ][c d ]]
现在我想迭代Map&lt;字符串,字符串&GT;和地图&lt;串,地图&LT;字符串,字符串&GT;&GT;同样,我试过了:
import java.util.*;
public class Test{
public static void print(Object obj) {
if(obj instanceof Map){
System.out.print("{");
Map map=(Map)obj;
for(Map.Entry<Object,Object> entry : map.entrySet()){
print(entry.getKey());
System.out.print(":");
print(entry.getValue());
System.out.print(",");
}
System.out.print("}");
}else{
System.out.print(obj);
}
}
public static void main(String[] args){
String m0="a";
print(m0);
System.out.println("");
Map<String,String> m1=new HashMap<String,String>();
m1.put("surname","Tom");
m1.put("lastname","Bob");
print(m1);
System.out.println("");
Map<String,HashMap<String,String>> m2=new HashMap<String,HashMap<String,String>>();
HashMap<String,String> mm1=new HashMap<String,String>();
mm1.put("surname","Tom");
mm1.put("lastname","Bob");
mm1.put("nickname","Penguin");
m2.put("owner",mm1);
HashMap<String,String> mm2=new HashMap<String,String>();
mm2.put("name","Lucky");
mm2.put("type","cat");
m2.put("pet",mm2);
print(m2);
}
}
预期输出类似于:
a
{surname:Tom,lastname:Bob,}
{owner:{surname:Tom,nickname:Penguin,lastname:Bob,},pet:{name:Lucky,type:cat,},}
但无法编译:
Test.java:20: error: incompatible types: Object cannot be converted to Entry<Object,Object>
for(Map.Entry<Object,Object> entry : map.entrySet()){
是什么原因?有可能解决它吗?如果没有,我怎么能递归地迭代嵌套映射,就像在显示的开头递归迭代List一样?
答案 0 :(得分:0)
Map
与Map<Object,Object>
不同。
它会转换为Map<Object,Object>
或使用Entry
而不使用泛型。
答案 1 :(得分:0)
这里:
public static void print(Object obj) {
if(obj instanceof Map){
System.out.print("{");
Map map=(Map)obj; // <-- raw map
....
你申报原始Map
它具有重要的后果,因为编译器将绑定声明对象的方法而不考虑泛型。
以下是entrySet()
界面中声明的Map
方法:
Set<Map.Entry<K, V>> entrySet();
这种方法如下所示:
Set entrySet();
所以这段代码无法编译:
for (Map.Entry<Object, Object> entry : map.entrySet()) {
因为您操纵原始Set
。
要解决您的问题,您可以将Map
转换为Map<Object,Object>
或更好Map<?, ?>
:
Map<?, ?> map = (Map<?, ?>) obj;
for (Map.Entry<?, ?> entry : map.entrySet()) {
print(entry.getKey());
System.out.print(":");
print(entry.getValue());
System.out.print(",");
}