I have written this piece of code to demonstrate:
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();
list2.add(list1);
list1.add(list2);
list1.toString();
This code will cause the StackOverflowError.
However I am aware there is some effort in java's collections to prevent this, for example this code will work fine:
List<Object> list1 = new ArrayList<>();
list1.add(list1);
list1.toString();
Some other languages seem to handle it as well (both cases). Is there a reason the first example is not "sanitized" and the second one is? Is it a bug?