我正在尝试获取列表的大小,但出现错误:
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()
将始终 eval 为true
,将您for
变成无限循环,其调用堆栈最终会耗尽 JVM 的内存。
如果您只想为列表的初始长度重复 for 循环,只需将该值保存到循环之前的变量中并使用它而不是 .size()
int len = items.size();
for(int j = 0; j < len; j++){
items.add(width, "\n");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句