I and getting java.lang.StackOverflowError
while executing below code,
public class Insertion {
private static ArrayList integers1 = new ArrayList();
private static ArrayList integers2 = new ArrayList();
public static void main(String[] args) {
Collections.addAll(integers1, 1, 2, 3);
Collections.addAll(integers2, 5, 6, 7);
integers1.add(integers2);
System.out.println(integers1);
integers2.add(integers1);
System.out.println(integers2);
}
}
Please explain why?
The StackOverflow is happenning when you try to print the list.
You have two lists: integers1=[1,2,3,integers2]
and integers2=[5,6,7,integers1]
When you try to print integers2
, you actually print:
[1,2,3,integers1.toString()]
and integers1.toString()
is [5,6,7,integers2.toString()]
, which in its turn invoke integers1.toString()
again and again. This results in infinite loop that ends only when stack is overflowed.
The theoretical result of this print will be [1,2,3,5,6,7,1,2,3,5,6,7,... (infinite repeat)]
, and this is done via recursion - but at some point, the stack is full and the program breaks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With