我正在编写一个递归函数,其目的是遍历 pList 文件.我的代码是
I am writing a recursive function whose purpose is to iterate over the pList File. My code is
public static void HashMapper(Map lhm1) throws ParseException {
//Set<Object> set = jsonObject.keySet();
for (Object entry : lhm1.entrySet()) {
if(entry instanceof String)
{
System.out.println(entry.toString());
}
else
{
HashMapper((Map) ((Map) entry).keySet()); //getting Exception java.util.HashMap$HashMap Entry cannot be cast to java.util.Map
}
}
}
但是当我调用我的函数HashMapper((Map) ((Map) entry).keySet());"时.我得到了一个例外
But when i am calling my function "HashMapper((Map) ((Map) entry).keySet());". I am getting an exception of
java.util.HashMap$HashMap 条目不能转换为 java.util.Map
java.util.HashMap$HashMap Entry cannot be cast to java.util.Map
我不知道如何调用我的函数以及如何将 Hashmap 条目转换为 Map
I donot know how to call my function and how can i convert Hashmap entry to Map
Entry 确实不是String
.它是 Map.Entry
,因此您可以根据需要将其转换为这种类型.
Entry is indeed not String
. It is Map.Entry
, so you can cast it to this type if you need.
但是自从大约 10 年前引入的 java 1.5 以来,您几乎不需要强制转换.而是使用泛型定义映射并使用类型安全编程.
However since java 1.5 that was introduced ~10 years ago you almost do not really need casting. Instead define map with generic and use type-safe programming.
很遗憾,您的代码不是很清楚.您的意思是您的地图的键或值是 String
吗?假设键是字符串,值可以是字符串或映射.(顺便说一句,这是非常糟糕的做法,所以我建议您在描述您的任务时提出其他问题,并询问如何设计您的程序.)
Unfortunately your code is not so clear. Do you mean that key or value of your map is String
? Let's assume that key is string and value can be either string or map. (BTW this extremely bad practice, so I'd recommend you to ask other question where you describe what your task is and ask how to design your program.)
但无论如何,到目前为止我可以建议你:
But anyway here is what I can suggest you so far:
public static void hashMapper(Map<String, Object> lhm1) throws ParseException {
for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
System.out.println(value);
} else if (value instanceof Map) {
Map<String, Object> subMap = (Map<String, Object>)value;
hashMapper(subMap);
} else {
throw new IllegalArgumentException(String.valueOf(value));
}
}
}
这篇关于Map Java 的递归迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!