Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can java.util.LinkedList have a Loop?

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?

like image 794
vikky.rk Avatar asked Dec 28 '25 04:12

vikky.rk


2 Answers

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.

like image 62
Esben Skov Pedersen Avatar answered Dec 30 '25 16:12

Esben Skov Pedersen


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.

like image 42
Alex Gitelman Avatar answered Dec 30 '25 16:12

Alex Gitelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!