Java LinkedList

The LinkedList class provides a linked-list data structure and implements the List interface. It can have duplicate elements. The LinkedList is based on containers. The elements are saved in containers. Each container links to the next container. It is a part of the java.util package i.e., you need to import the java.util.LinkedList package.

Let us see some LinkedList methods/  operations with examples:

  • Create a LinkedList
  • Size of a LinkedList
  • Loop through the LinkedList
  • Add an item to the beginning of the LinkedList
  • Add an item to the end of the LinkedList
  • Remove an item from the beginning of the LinkedList
  • Remove an item from the end of the LinkedList
  • Get the item at the beginning of the LinkedList
  • Get the item at the end of the LinkedList

Let us first see how to create a LinkedList in Java:

Create a LinkedList

To create a LinkedList, set the type in angular braces i.e., use the wrapper class. For example, for creating a LinkedList with string elements, use <String>:

Let us now see an example and create a LinkedList in Java with string elements:

Output

Size of a LinkedList

To get the size of a LinkedList i.e., how many elements it has, use the size() method. Let us see an example:

Output

Loop through the LinkedList

Use the for loop to loop through the LinkedList in Java. Let us see an example:

Output

Add an item to the beginning of the LinkedList

The addFirst() method in Java adds an item to the beginning of the LinkedList. Let us see an example:

Output

Add an item to the end of the LinkedList

The addLast() method in Java adds an item to the end of the LinkedList. Let us see an example:

Output

Remove an item from the beginning of the LinkedList

The removeFirst() method in Java is used to remove an item from the beginning of the LinkedList. Let us see an example:

Output

Remove an item from the end of the LinkedList

The removeLast() method in Java is used to remove an item from the end of the LinkedList. Let us see an example:

Output

Get the item at the beginning of the LinkedList

The getFirst() method in Java is used to get an item at the beginning of the LinkedList. Let us see an example:

Output

Get the item at the end of the LinkedList

The getLast() method in Java is used to get an item at the end of the LinkedList. Let us see an example:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java Method Overloading
Java ArrayList
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading