我使用以下代码使用hashmap删除传递性child->父关系。 (hashmap数据集是以child->父条目表示的。)
private static void factor_transitivity(Map<String,String> dataset, boolean complete) {
if (!complete) {
complete = true; // Assume that on this check everything will come out to be OK.
for (Map.Entry<String, String> pair : dataset.entrySet()) {
if (dataset.containsKey(pair.getValue())) {
complete = false;
String value = dataset.get(pair.getValue());
dataset.put(pair.getKey(),value);
//System.out.print("");
break;
}
}
factor_transitivity(dataset, complete);
}
}
请注意评论
//System.out.println("")
线。如果我取消注释该行,那么代码工作正常。但是,如果我留下评论,那么我会收到如下错误消息:
Exception in thread "main" java.lang.StackOverflowError
at java.util.HashMap.hash(HashMap.java:362)
at java.util.HashMap.getEntry(HashMap.java:462)
at java.util.HashMap.get(HashMap.java:417)
为什么我会遇到这种奇怪的行为?
答案 0 :(得分:-1)
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
factor_transitivity(new HashMap<String,String>(){{
put("abc","abc");
put("ghi","ghi");
}},false );
}
private static void factor_transitivity(Map<String,String> dataset, boolean complete) {
if (!complete) {
complete = true; // Assume that on this check everything will come out to be OK.
for (Map.Entry<String, String> pair : dataset.entrySet()) {
if (dataset.containsKey(pair.getValue())) {
complete = false;
String value = dataset.get(pair.getValue());
dataset.put(pair.getKey(),value);
System.out.print("hello");
break;
}
}
factor_transitivity(dataset, complete);
}
}
}
现在你可以看到这个代码是递归的,它不断调用factor_transitivity方法并打印&#34; hello&#34;一次又一次。即使我注释掉该行,由于该方法的递归性质,也会出现相同的错误(http://ideone.com/ffA0pG)。