While learning Self Referential Collection I come up with where it is throwing Stack overflow error.
Please find the source code below.
import java.util.*;
public class TestSelfColl {
public static void main(final String[] args) {
test(new ArrayList<Collection<?>>());
test(new LinkedList<Collection<?>>());
test(new HashSet<Collection<?>>());
test(new LinkedHashSet<Collection<?>>());
}
private static void test(final Collection<Collection<?>> collection) {
collection.add(collection);
System.out.println(collection);
try {
System.out.println(collection.hashCode());
} catch (final StackOverflowError err) {
System.out.println(err + " for " + collection.getClass());
}
}
}
Really want to know why this error is coming .
My expectation was i will get Output as :
[(this Collection)]
123
..
But in contrast i am getting ..
[(this Collection)]
java.lang.StackOverflowError for class java.util.ArrayList
...