Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why LinkedList in Java is not a real Linked List?

By definition Linked List is a list that each element of it refers to the next element (and previous element if we are talkin about double linked list.) http://en.wikipedia.org/wiki/Linked_list

However, in Java LinkedList is implementing List, Queue, Deque and more. http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html

You can not find a method in LinkedList that gives you next or previous object in the list, the best you can do is to get an Iterator and get objects. My question is why Java has called this data structure LinkedList, while it is not truly a linked list? A linked list can be implemented in Java like this:

Public class MyLinkedList{
 public int value;
 public MyLinkedList next;
}
like image 419
sheidaei Avatar asked Feb 11 '13 16:02

sheidaei


1 Answers

You can not find a method in LinkedList that gives you next or previous object in the list

No, and that's entirely appropriate. The idea of "next item in a list" doesn't make sense on a list. It makes perfect sense for a node within a list, but that's not something which is exposed by the Java API. It's present internally, of course - just not exposed. If you want to iterate over the list, you use an iterator. You can still add at the start or end, remove from the start or end, and add/remove from the iterator.

While you certainly can conflate the concepts of "node" and "list" as your suggested sample code does, I don't think it's generally a good idea.

To put it another way: what are you trying to achieve that's causing you problems? I believe you should be able to do what you want using the public API - you may just not have noticed it all.

like image 162
Jon Skeet Avatar answered Oct 22 '22 17:10

Jon Skeet