Java 中迭代哈希集时出现 StackOverflow 异常
我正在尝试选择一些保存在哈希集中的称为元素的对象。我正在使用 foreach 迭代名为 elements 的哈希集,例如
for( Element e: elements).
这些选定的元素在 ArrayList
事实上,我不久前还没有任何问题。该方法通过了单元测试。然后,突然我开始收到该方法的 stackoverflow 异常。我调试了一下。我看到那里发生了一些奇怪的事情。
我正在填充一个数组列表,元素的迭代已完成。最后,该方法必须返回数组列表。但是,它开始重新迭代哈希集,并将 arraylist 设置为空。我不明白为什么会发生这种情况。我已经编程两年了,这是我第一次看到这种奇怪的事情。
如果您想看一下,这是代码:
public ArrayList<Element> addNextLeftElements(Element firstEl, HashSet<Element> elements, ArrayList<Element> el) {
for (Element nextEl : elements) {
if (!nextEl.equals(firstEl)) {
if (nextEl.overlaps(firstEl, ac.absPrecision)) {
el.add(nextEl);
} else {
for (double dis = 16.0; dis <= 18.1; dis += 0.1) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
for (int displus = 9; displus <= 11; displus++) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
}
}
}
}
}
return(el);
}
提前致谢
I am trying to select some objects called elements kept in a hashset. I am iterating over the hashset called elements with foreach like
for( Element e: elements).
These selected elements are handled in an ArrayList<Element> el
.
Actually, I haven't any problems a while ago. The method passed from unit tests. Then, suddenly I started to get stackoverflow exception for the method. I debugged. I saw something strange going on there.
I am filling an arraylist and iteration of the elements is finished. Finally, the method must return the arraylist. However, it starts to re-iterate the hashset with setting arraylist empty. I did not understand why this happens. I have been programming for 2 years and this is the first time that I saw this strange thing.
Here is the code if you want to have a look at:
public ArrayList<Element> addNextLeftElements(Element firstEl, HashSet<Element> elements, ArrayList<Element> el) {
for (Element nextEl : elements) {
if (!nextEl.equals(firstEl)) {
if (nextEl.overlaps(firstEl, ac.absPrecision)) {
el.add(nextEl);
} else {
for (double dis = 16.0; dis <= 18.1; dis += 0.1) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
for (int displus = 9; displus <= 11; displus++) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
}
}
}
}
}
return(el);
}
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个功能本身就很好。
java 中的 StackOverFlow 异常几乎总是由无限循环触发,因此请检查您调用的函数之一是否重新调用了 addNextLeftElements。像这样运行函数,只需查看堆栈即可知道哪些函数导致溢出。
}
This function as it is, is fine.
StackOverFlow exceptions in java are almost always triggered by an infinite loop, so look if one of the functions you call re-calls addNextLeftElements. run the function like this, and simply look at the stack so you know what functions are causing the overflow.
}