Table of Contents
Methods of LinkedList in Java
Examples of LinkedList in Java
Example #3
Conclusion
Home Java javaTutorial LinkedList in Java

LinkedList in Java

Aug 30, 2024 pm 03:48 PM
java

LinkedList in Java is linear data structures that are different from arrays. There are certain advantages as well as disadvantages of using Linked List in a Java program. Each element in a linkedlist is stored in a cell known as Node. Each node has a specific address. The main disadvantage of LinkedList is that the nodes are not easily accessible at each point.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

There are pointers that are used to address each node, and to access a specific node, there has to start from the head, and then the specific pointer to which the node is to be accessed is reached. The LinkedList class also consists of many constructors and methods like other Java interfaces. In this article, we are going to see two constructors which are being used in LinkedList.

They are:

  • LinkedList(): This is used for assigning an empty LinkedList().
  • LinkedList(Collection C): This is used to create an ordered list containing all elements of a specified collection, as returned by the collection’s iterator.

Methods of LinkedList in Java

There are many methods or functions which are part of the Java LinkedList class. We will see some of the functions that are part of the Java LinkedList class in this article.

They are:

  • add(int a, I Element): This method is used for inserting a specific element at the specific position in this list.
  • add( E e): This method fixes the specified element to the end of the list.
  • add(int index, Collection C): This method inserts all the specified elements in the list, starting from the starting position.
  • offerFirst​(): This method Inserts the specified element at the front of this list.
  • addLast(): This method is used for inserting an element at the end of the list.
  • void clear(): This method is used for removing all the elements from the Linkedlist.
  • poll​(): It removes the first element of a list.
  • lastIndexOf​(): Used for returning the index of the last occurrence of the specified element in this list.
  • getLast(): This function is used for returning the last element in the LinkedList.
  • offer​(): This method inserts the specified element as the tail element of the list.
  • offerLast​(): This method Inserts the specified element at the end of this list.
  • peek​(): It retrieves the first element of a list.
  • peekFirst​(): This method is used for retrieving the last element of a list or return null if the list is empty.
  • addFirst(): This method is used for inserting the element at the beginning of the list.
  • peekLast​(): This method is used for retrieving the last element of the list or return null if the list is empty.
  • pollFirst​(): This method is used for retrieving and removing the first element of this list or returns null if this list is empty.
  • contains(): This function returns true if the LinkedList contains the specific element at the node.
  • pollLast​(): This method removes the last element of this list or returns null if this list is empty.
  • removeFirst​(): This method returns the first element from this list.
  • element(): This method retrieves but does not remove the head of the list.
  • getFirst(): This method is used for returning the first element of the LinkedList.
  • remove​(): This method removes the first element of the LinkedList.
  • remove​(int index): This method removes the element at the specified position in this list.
  • removeLast​(): This method returns the last element from this list.
  • set​(int index, E element): This method replaces the element at the specified position in this list with the specified element.
  • size​(): This method returns the number of elements in this list.

Examples of LinkedList in Java

Given below are the examples mentioned:

Example #1

In this coding example, we are going to see the LinkedList methods of inserting certain elements in the linkedlist and then removing them, and finally displaying the linkedlist.

Code:

import java.util.*;
public class Example3
{
public static void main(String args[])
{
LinkedList<String> object = new LinkedList<String>();
// Adding elements to the linked list
object.add("A");
object.add("B");
object.addLast("C");
object.addFirst("D");
object.add(2, "E");
object.add("F");
object.add("G");
System.out.println("Linked list : " + object);
object.remove("C");
object.remove(3);
object.removeFirst();
object.removeLast();
System.out.println("Linked list after deletion: " + object);
}
}
Copy after login

Output:

LinkedList in Java

In the sample output, we see that there are certain elements in the linkedlist, and finally, certain elements are deleted, and then the linkedlist after all the deletion of the elements is shown.

Example #2

In this program, we are going to see four names being printed using sequential order in LinkedList. We use a String LinkedList and use it to print names that can be of any number. We use the While loop here for printing the names which are present in the program.

Code:

import java.util.*;
public class LinkedList1
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();
al.add("Ishankamal Mitra");
al.add("Sourya Mukherjee");
al.add("Satyaki Das");
al.add("Debodooty Sarkar");
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Copy after login

Output:

LinkedList in Java

In this program, we check how the coding helps us to print four names in sequential order as mentioned in the LinkedList. In the next program, we are going to see how the sequence is changed; that is, the names are printed in reverse order of the input.

Example #3

In this code, the program inputs the name and then prints the names in the reverse order of their sequence.

Code:

import java.util.*;
public class LinkedList4
{
public static void main(String args[])
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ishankamal Mitra");
ll.add("Sourya Mukherjee");
ll.add("Satyaki Das");
//Going through the list of elements in Reverse order
Iterator i=ll.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Copy after login

Output:

LinkedList in Java

In this program, we use the DescendingIterator(), and we use it to print the names in the reverse order of the input. We can see it very clearly through the program.

Conclusion

In this article, we saw the different constructors and methods which are present in the LinkedList class. Plus, we saw a Java program to illustrate the insertion and deletion of elements in a LinkedList. We also saw the advantages and disadvantages of using LinkedList over arrays. They contain nodes that are not easily accessible and have to be accessed through the LinkedList head. We also notice three examples of coding where names are printed in reverse order, sequential order, and removing elements from a LinkedList. These programs help us to understand the methodology of the LinkedList class.

The above is the detailed content of LinkedList in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles