I'm using a recursive function, an开发者_开发技巧d I'm getting this error when I execute :
Exception in thread "main" java.lang.StackOverflowError
at java.util.HashMap$Entry.<init>(Unknown Source)
at java.util.HashMap.addEntry(Unknown Source)
at java.util.HashMap.put(Unknown Source)
I debeugged the method and 100% sure it ends at some point.
So I think its related to a memory problem.
Is there any solution ?
EDIT:
public static Vector<String> _toOpen;
public static void openFiles(Vector<String> files)
{
...
while(actualFile.hasNext)
{
if(!_toOpen.contains(word))
{
_toOpen.add(word);
System.out.println("word");
}
}
...
if(_toOpen.size() > 0)
{
openFiles(_toOpen);
}
}
At the first call I pass to OpenFiles a Vector wich contains a list of files to open, each file has a list of files to open again and so on ...
What I'm doing is preventing a file to be opened if it was dopne before.
Looking at your code - is there any conditional (e.g. if
for example) on your final call to openFiles(_toOpen)
?
If not, then every time openFiles
is called, it will call itself recursively. No matter what the maximum size of the stack, this method will never actually return and you've effectively got an infinite loop.
And if there is some conditional beforehand, you're evidently getting into a situation where it's consistently evaluating to a true
(or whatever leads to the recursive call being made).
Asides from that, it looks like you could restructure your code to avoid this. What it is you're trying to do with _toOpen
? Why do you appear to ignore the files
argument passed in (I appreciate there is elided code, and presumably the contents get copied to _toOpen
, but this seems unusual to say the least).
A recursive call does not seem like it's the best way to approach this problem, unless you have some strange situation such as files that refer to other files to open.
I think the problem is in your logic and the test for _toOpen.size() > 0
.
After you perform _toOpen.add(word);
then _toOpen.size()
will always be greater than 0, and thus the if
condition always true, and the function will always recurse.
You say "But the _toOpen.add(word);
is not triggered always" - but it has to be triggered only once in the application life cycle to make this method recurse indefinitely.
Your Vector _toOpen is static which means there is only one of it, which means that as soon as _toOpen.add(word);
is triggered, the statement _toOpen.size() > 0
always holds true.
精彩评论