Home  >  Article  >  Java  >  How many ways are there to iterate over a LinkedList in Java?

How many ways are there to iterate over a LinkedList in Java?

WBOY
WBOYforward
2023-09-15 13:53:12516browse

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.

Using Iterator

We can traverse the elements of LinkedList through the Iterator class.

Example

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());
      }
   }
}

Output

Kohli
Morgan
Williamson
Smith
Kohli

##Using ListIterator

We can iterate over LinkedList by

Elements of ListIterator class.

Example

import 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());
      }
   }
}

Output

Kohli
Morgan
Williamson
Smith
Kohli

##Sing For-each loop

We can also iterate LinkedList The elements are looped through

f

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);
      }
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete