简体   繁体   中英

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 {
    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.

您没有增加count变量。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM