开发者

Java do while loop arralyist problem

I want ask why Java heap space is triggered when executing "NAME.add("Tom");"?

<%@ page import="java.util.*" %>

<%
try开发者_Python百科 {
    ArrayList <String> NAME = new ArrayList<String>();
    int count= 0;

    do
    {
        NAME.add("Tom");
    } while ( count < 2);

    String[] name = NAME.toArray(new String[NAME.size()]);

%>

<script type="text/javascript">
    var output=[];
    <%int i = 0;%>

    <%while ( i < name.length ) { System.out.println(name[i]);%>
        output[<%=i%>] = [];
        output[<%=i%>][0] = '<%=name[i]%>';

    <% System.out.println("No exception in JAVASCRIPT.");i++;}%>
</script>

<%
} catch (Exception error ){System.out.println(error);}%>


Notice that in this code:

int count= 0;

do
{
    NAME.add("Tom");
} while ( count < 2);

You never change the value of count anywhere, and so this loop will loop forever. If you change the code so that you change count somehow (perhaps by using a for loop to count upwards), this should go away. The JVM is probably running out of heap space by adding as many copies of Tom as it can to the collection, eventually exhausting available memory.


You're not incrementing the count variable.


Look at this code

int count= 0; do { NAME.add("Tom"); } while ( count < 2);

You forget to increment count. So in your code, it will do an infinite loop and all your memory will be taken.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜