java.lang.OutOfMemoryError in my for loop

这一生的挚爱 提交于 2019-12-11 17:54:42

问题


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"

Here is my code:

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

What am I doing wrong here?


回答1:


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.

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



回答2:


My understanding of what you want.

   public void wrapText(String text, int width)
      {
        String resultingString="";
        for(String item : text.split(" ")){
            resultingString +=  item +"\n";
        }
        System.out.println(resultingString);
        /* this method needs to be improved - it currently does not wrap text */
      //  System.out.println(text);
      }



回答3:


The reason you get this error is because you have an infinite loop. items.size() will always be bigger than j.

That's because you add an item to the list, which means you add 1 to it's size and since you also add 1 to j on each loop iteration, j will never become bigger than the list's size. Therefore, the loop will never stop. You can add a variable int size = items.size() and then put that in the loop instead of items.size() like the following :

List<String> items = new LinkedList<>(Arrays.asList(text.split(" ")));
int size = items.size();
for(int j = 0; j < size; j++){
    items.add(width, "\n");
}
System.out.println(items);

This will get rid of the error you're having



来源:https://stackoverflow.com/questions/52302210/java-lang-outofmemoryerror-in-my-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!