問題描述
我正在編寫一個(gè)遞歸函數(shù),其目的是遍歷 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
}
}
}
但是當(dāng)我調(diào)用我的函數(shù)HashMapper((Map) ((Map) entry).keySet());"時(shí).我得到了一個(gè)例外
But when i am calling my function "HashMapper((Map) ((Map) entry).keySet());". I am getting an exception of
java.util.HashMap$HashMap 條目不能轉(zhuǎn)換為 java.util.Map
java.util.HashMap$HashMap Entry cannot be cast to java.util.Map
我不知道如何調(diào)用我的函數(shù)以及如何將 Hashmap 條目轉(zhuǎn)換為 Map
I donot know how to call my function and how can i convert Hashmap entry to Map
推薦答案
Entry 確實(shí)不是String
.它是 Map.Entry
,因此您可以根據(jù)需要將其轉(zhuǎn)換為這種類型.
Entry is indeed not String
. It is Map.Entry
, so you can cast it to this type if you need.
但是自從大約 10 年前引入的 java 1.5 以來,您幾乎不需要強(qiáng)制轉(zhuǎn)換.而是使用泛型定義映射并使用類型安全編程.
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
嗎?假設(shè)鍵是字符串,值可以是字符串或映射.(順便說一句,這是非常糟糕的做法,所以我建議您在描述您的任務(wù)時(shí)提出其他問題,并詢問如何設(shè)計(jì)您的程序.)
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));
}
}
}
這篇關(guān)于Map Java 的遞歸迭代的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!