Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Util Linked List - how to find next?

Tags:

When using Java LinkedList how do you find out the element's next or previous relationships?

I mean, in a regular linked list I would do something like this:

Node node1 = new Node(); Node node2 = new Node(); LinkedList list = new LinkedList(); list.add(node1); list.add(node2);  //then my node1 will know who it's next is: assertEquals(node2, node1.next()); 

where Node is my own container for data/object.

But in Java's LinkedList, the data does not seem to be modified. So how do I actually find out who the "next" (or "previous" in the case of doubly-linked lists) element is?

like image 299
Andriy Drozdyuk Avatar asked Feb 07 '11 23:02

Andriy Drozdyuk


People also ask

How do you find the next item in a linked list?

LinkedList implements the Collection (and List) interface, so given an index i of an element in the list list , you can get previous and next elements with list. get(i-1) and list. get(i+1) , respectively.

What is getNext () in Java?

getNext(); sets the value of second element of the LinkedList link into edgeLine , and then you loop and do the same, and then the same over and over and over again.

How can I search for data in a linked list in Java?

Create a LinkedList class and initialize the head node to null. Create the required add and search functions. Initialize the LinkedList in the main method. Use the search method to find the element.

How do you find the index of an element in a linked list?

LinkedList. indexOf(Object element) method is used to check and find the occurrence of a particular element in the list. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the list does not contain the element.


1 Answers

You can't. LinkedList is just an implementation of List and offers about nothing more. You'd need to make your own.

For node1.next() you'd need a reference from node1 to the List. Actually, you'd need multiple references, since node1 may be there multiple times. Moreover, it may be contained in multiple Lists.

Maybe you can use ListIterator for this.

like image 106
maaartinus Avatar answered Nov 11 '22 05:11

maaartinus