Hi I have come across a question in a collection which says: One can add a reference of a collection to itself. Is it true or false? I read the explanation that, we can add the reference to the collection to itself, but it results in the stack overflow of the JVM. Please people tell me what is the correct answer, i am confused because we can add the reference but we should not add it. Please help me
Please read your private messages regarding an important announcement.
Thank you,
Rob
Originally posted by priti sh: Hi I have come across a question in a collection which says: One can add a reference of a collection to itself. Is it true or false? I read the explanation that, we can add the reference to the collection to itself, but it results in the stack overflow of the JVM. Please people tell me what is the correct answer, i am confused because we can add the reference but we should not add it. Please help me
Sure you can add a reference to a collection; the collection is an Object just as all of its elements. But there is indeed danger of stack overflow. It doesn't have to happen though; the toString implementation of AbstractCollection handles this as follows:
Line 10 has a special check to try to prevent stack overflows. Without this check, inside this toString method the same toString method would be called - and again, and again, and again.
It's still possible though:
So you are right to be very careful. [ October 16, 2008: Message edited by: Rob Prime ]