hw
always references the same one object, so even though you're adding 10^6 items (and thus have ~10^6 nodes internally), you'll only have one String
object allocated -- lots of references to that one object, but just that one object.
In fact, even if you did something like:
for (i=0;i<10**6;i++) {
String hs = "Hello, world."
myDq.addToEnd(hw);
}
You'd only have one String
because of string interning: all equal string literals across the whole JVM use the same one String
object.
I suspect you'll get the same OOM if you change it a bit to:
for (i=0;i<10**6;i++) {
String hs = new String("Hello, world.".toCharArray());
myDq.addToEnd(hw);
}
That allocates a new String
each time, with a copy of the original String
's char array.
(OOM is a common nickname for OutOfMemoryError
, which is what Java throws when it's run out of heap space and can't reclaim enough through the garbage collector (GC). In this case, the list and all the objects reachable through it -- the internal node objects, the Integer
or String
values, etc -- can still be reached by the program and thus can't be GC'ed, so the JVM has nowhere to turn to for more heap space.)