我的for循环中的java.lang.OutOfMemoryError [英] java.lang.OutOfMemoryError in my for loop
本文介绍了我的for循环中的java.lang.OutOfMemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取列表的大小,但出现错误:
I'm trying to get the size of a list but I get the error:
Java HotSpot(TM) 64-Bit Server VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal UNKNOWN to handler- the VM may need to be forcibly terminated
Exception in thread "main"
这是我的代码:
public void wrapText(String text, int width)
{
List<String> items = new LinkedList<String>(Arrays.asList(text.split(" ")));
for(int j = 0; j < items.size(); j++){
items.add(width, "\n");
}
System.out.println(items);
/* this method needs to be improved - it currently does not wrap text */
// System.out.println(text);
}
我在做什么错了?
推荐答案
每次迭代时,您都在列表中添加了一个元素,因此增加了它的大小.在每次迭代结束时,j < items.size()
总是等于true
,将您的for
变成无限循环,其调用堆栈最终将耗尽JVM的内存.
Every iteration, you are adding an element on your list, hence increasing it's size. At the end of each iteration, j < items.size()
will always eval to true
, turning your for
into an infinite loop, which its call stack will eventually drain JVM's memory.
如果只想对列表的初始长度重复for循环,只需将该值保存到循环之前的变量中,然后使用它代替.size()
If you want to repeat your for loop only for the initial length of your list, just save that value into a variable prior to the loop and use that instead of .size()
int len = items.size();
for(int j = 0; j < len; j++){
items.add(width, "\n");
}
这篇关于我的for循环中的java.lang.OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文