Assuming I am using a single threaded application, can java.util.LinkedList have a loop? I see in the source code that Entry is a private inner class, so there is no way to tamper it. Just wondering, finding a loop in a linked is such a popular question for interviews. Nobody asks how to design a list to avoid having loops in the first place. Or am I misunderstanding something here?
You are right since j.u.LinkedList does not expose an api for creating lops it is not supported. Maybe with some reflection violence it might happen.
I think the question comes from a generation of c programmers with a standard library with no linked list, who would often roll their own. Also since there is no private modifier in C it is always possible to create a loop in a C linked list if you wanted to.
You can avoid loop in linked list by providing interface that is not exposing specific list implementation. That's what happens in Java. java.util.List is an interface and java.util.LinkedList is just one of implementations which really does not expose much outside of main List inteface.
Interviews or computer science classes are mostly interested in theoretical implementations of linked list where you can link nodes whichever way you are pleased.
So to answer your question: no you can't have a loop in java.util.LinkedList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With