JAVA:去掉map重复value时,报java.lang.StackOverflowError,求问 怎么优化下面代码?

public static IdentityHashMap<String, JSONObject> removeRepetitionFromMap(IdentityHashMap<String, JSONObject> map) {int i = 0 ;
Set<Entry<String, JSONObject>> set = map.entrySet();
List<Entry<String, JSONObject>> list = new ArrayList<Entry<String, JSONObject>>(set);
Collections.sort(list, new Comparator<Entry<String, JSONObject>>() {
public int compare(Entry<String, JSONObject> entry1, Entry<String, JSONObject> entry2) {
return Integer.valueOf(entry1.getValue().hashCode()) - Integer.valueOf(entry2.getValue().hashCode());
}
});
for (int index = 0; index < list.size(); index++) {
String key = list.get(index).getKey();
JSONObject value = list.get(index).getValue();
int next_index = index + 1;
if (next_index < list.size()) {
String next_key = list.get(next_index).getKey();
JSONObject next_value = list.get(next_index).getValue();
System.out.println("Is Equal ? :"+(value.toString().equals(next_value.toString()) ));
if (value.toString().equals(next_value.toString())) {
Dup = true;
if (key.hashCode() < next_key.hashCode()) {
map.remove(next_key);
list.remove(next_index);
} else {map.remove(key); list.remove(index); } index--; duplicateRequestArray.add(value); i++;

} else{ Dup = false; } } }
ArrayList<JSONObject> jsonList = new ArrayList<JSONObject>();
Iterator<Entry<String, JSONObject>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JSONObject> entry = iterator.next();
JSONObject value = entry.getValue();
jsonList.add(value);
}
size:"+removeDuplicate(jsonList).size());
if(map.size()!=(removeDuplicate(jsonList).size())){
removeRepetitionFromMap(map);
}
return map;
}有时报错

第1个回答  2015-04-08

     StackOverflowError是因为递归深度过大导致的。请改成非递归算法。

    代码一片混乱。。请把源码文件发到百度网盘 然后在这里贴共享链接。

追问

囧,公司把云禁了..留个邮箱可好?

追答

我的意思是题主先改成非递归,有问题再贴上来。
这个递归的就不看了,看了也没用。
要邮箱的话到私信里聊。

本回答被网友采纳
相似回答