Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackOverflow exception while adding one array list to another

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?

like image 461
Rajib Deka Avatar asked Nov 29 '22 14:11

Rajib Deka


1 Answers

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.

like image 57
amit Avatar answered Dec 11 '22 04:12

amit