Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

java Linked List

Java LinkedList

In the preceding chapter, you became acquainted with the ArrayList class. The LinkedList class shares considerable similarity with ArrayList.

Example

 // Import the LinkedList class
import java.util.LinkedList;
 public class Main {
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  }
}

ArrayList vs. LinkedList

In the preceding chapter, you became acquainted with the ArrayList class. The LinkedList class shares considerable similarity with ArrayList.

The LinkedList class possesses identical methods to the ArrayList class since they both implement the List interface. This implies that you can add, modify, remove, and clear items from the list in the same manner.

Although the ArrayList class and the LinkedList class can be utilized in a similar manner, they are constructed in fundamentally different ways.

How the ArrayList works

Within the ArrayList class, there exists a conventional array. Upon adding an element, it is inserted into this array. If the array’s capacity is insufficient, a new, larger array is generated to substitute the old one, which is then discarded.

How the LinkedList works

In a LinkedList, items are stored in “containers.” The list maintains a reference to the first container, and each container holds a reference to the next container in the list. When adding an element to the list, it is placed into a new container, which is then linked to another container in the list.

When To Use

Utilize an ArrayList for storage and access of data, and LinkedList for data manipulation.

LinkedList Methods

In many situations, the ArrayList is preferable due to the frequent need for random access to items in the list. However, the LinkedList offers various methods optimized for certain operations’ efficiency.

Method

Description

addFirst()

Insert an item at the start of the list.

 addLast()

Append an item to the end of the list.

removeFirst()

Remove an item from the beginning of the list.

removeLast()

Remove an item from the end of the list.

getFirst()

Retrieve an item at the beginning of the list.

getLast()

Retrieve an item at the end of the list.