Home >Java >javaTutorial >How many ways are there to iterate over a LinkedList in Java?
A LinkedList is a data structure that contains a set of nodes connected by pointers, arranged in order. A LinkedList can be used as a dynamic array, which allocates independent space for each element in its own memory block, which is called a Node. Each node contains two fields, a "data" field is used to store the element type held by the list, and a "next" field is a pointer used to One node is linked to the next node.
We can use three ways to traverse the elements of LinkedList in Java.
We can traverse the elements of LinkedList through the Iterator class.
import java.util.*; public class LinkedListIteratorTest { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("Kohli"); list.add("Morgan"); list.add("Williamson"); list.add("Smith"); list.add("Kohli"); <strong> </strong> Iterator it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }
Kohli Morgan Williamson Smith Kohli
##Using ListIterator
We can iterate over LinkedList byElements of ListIterator class.
Exampleimport java.util.*; public class LinkedListWithListIteratorTest { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("Kohli"); list.add("Morgan"); list.add("Williamson"); list.add("Smith"); list.add("Kohli"); <strong> </strong>ListIterator<String> li = list.listIterator(); while(li.hasNext()) { System.out.println(li.next()); } } }
Kohli Morgan Williamson Smith Kohli
##Sing For-each loop
or-each. Example
import java.util.*; public class LinkedListForEachTest { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("Kohli"); list.add("Morgan"); list.add("Williamson"); list.add("Smith"); list.add("Kohli"); <strong> </strong> for(String str : list) { System.out.println(str); } } }
Kohli Morgan Williamson Smith Kohli
The above is the detailed content of How many ways are there to iterate over a LinkedList in Java?. For more information, please follow other related articles on the PHP Chinese website!