gpt4 book ai didi

java - 如何使用相同的递归函数迭代 Map 和 Map> ?

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:27 27 4
gpt4 key购买 nike

例如,为了使用相同的函数迭代 List< String> 和 List< List< String>> ,我可以编写如下内容:

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< String,String> 和 Map< String,Map< String,String>> ,我尝试过:

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()){

这是什么原因呢?可以修复吗?如果没有,如何像在开头所示的递归迭代列表一样递归地迭代嵌套映射?

最佳答案

一个MapMap<Object,Object> 不同。

它会转换为 Map<Object,Object>或使用Entry没有泛型。

关于java - 如何使用相同的递归函数迭代 Map<String,String> 和 Map<String,Map<String,String>> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com