aspose file tools
The moose likes Beginning Java and the fly likes Need help in collection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Need help in collection" Watch "Need help in collection" New topic
Author

Need help in collection

Priti Sharma
Greenhorn

Joined: Oct 15, 2008
Posts: 15
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

Joined: Oct 27, 2005
Posts: 19216

"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 ]

SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32675
    
    4
Please read your private messages again (in a minute's time).

CR
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Need help in collection
 
Similar Threads
GC
Question for Wildcards in Collection
set lazy to false in runtime in Hibernate
Generics doubt
What is the use of "Collection.singleton" method?