Question about heap memory in Java
There was a question about heap memory
. So pay attention to the bold italics. in the 1st version, everything works fine. But in the second one, {[3] pops up]}
OutOfMemoryError: Java heap space.
Who can tell you why?
public class idea_test { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader("S:\\idea test\\src\\file.txt")); ArrayList strings = new ArrayList(); (1) String s; while ((s = reader.readLine()) != null){ strings.add(s); } (2) String s = reader.readLine(); while (s != null){ strings.add(s); } reader.close(); String[] strings1 = strings.toArray(new String[strings.size()]); Arrays.sort(strings1); for (String s1 : strings1) { System.out.println(s1); } } }
10
1 answers
Well, so elementary.
In the first case, we spin in a loop and call {[11] at each iteration]}
reader.readLine()
After that, we check s
for null
, if all the lines of the file were read((s = reader.readLine()) != null
== false
), then we safely fall out of the cycle.
In the second case, we get an infinite loop, since we once called
reader.readLine()
And then we spin endlessly in the loop (since s != null
is always true, because we are not changing s
), adding the same values to ArrayList
, which leads to OutOfMemoryError
33
Author: ermak0ff, 2015-11-04 09:42:10