• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help in collection  RSS feed

 
Priti Sharma
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"priti sh",

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 ]
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please read your private messages again (in a minute's time).

CR
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!