猿问

我的 for 循环中的 java.lang.OutOfMemoryError

我正在尝试获取列表的大小,但出现错误:


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);

  }

我在这里做错了什么?


噜噜哒
浏览 301回答 3
3回答

慕工程0101907

每次迭代,您都会在列表中添加一个元素,从而增加它的大小。在每次迭代结束时,j < items.size()将始终 eval 为true,将您for变成无限循环,其调用堆栈最终会耗尽 JVM 的内存。如果您只想为列表的初始长度重复 for 循环,只需将该值保存到循环之前的变量中并使用它而不是 .size()int len = items.size();for(int j = 0; j < len; j++){&nbsp; &nbsp; items.add(width, "\n");}

临摹微笑

您收到此错误的原因是因为您有一个无限循环。items.size()将永远大于 j。那是因为您向列表中添加了一个项目,这意味着您将其大小加 1,并且由于您还在每次循环迭代中将 1 加到 j,因此 j 永远不会变得大于列表的大小。因此,循环永远不会停止。您可以添加一个变量int size = items.size(),然后将其放入循环中,而不是items.size()像下面这样:List<String> items = new LinkedList<>(Arrays.asList(text.split(" ")));int size = items.size();for(int j = 0; j < size; j++){&nbsp; &nbsp; items.add(width, "\n");}System.out.println(items);这将消除您遇到的错误

慕慕森

我对你想要什么的理解。&nbsp; &nbsp;public void wrapText(String text, int width)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; String resultingString="";&nbsp; &nbsp; &nbsp; &nbsp; for(String item : text.split(" ")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resultingString +=&nbsp; item +"\n";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(resultingString);&nbsp; &nbsp; &nbsp; &nbsp; /* this method needs to be improved - it currently does not wrap text */&nbsp; &nbsp; &nbsp; //&nbsp; System.out.println(text);&nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答