In Java, LinkedList
is another implementation of the List
interface provided by the java.util
package. Unlike ArrayList
, which is backed by an array, LinkedList
is backed by a doubly-linked list, which provides better performance for certain operations like adding or removing elements from the beginning or middle of the list. Here's a basic overview of how to use LinkedList
:
import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // Create a LinkedList LinkedListlist = new LinkedList<>(); // Add elements to the LinkedList list.add("Apple"); list.add("Banana"); list.add("Orange"); // Access elements in the LinkedList System.out.println("Elements in the LinkedList:"); for (String fruit : list) { System.out.println(fruit); } // Get the size of the LinkedList int size = list.size(); System.out.println("Size of the LinkedList: " + size); // Remove an element from the LinkedList list.remove("Banana"); // Check if an element exists in the LinkedList boolean containsOrange = list.contains("Orange"); System.out.println("LinkedList contains Orange: " + containsOrange); // Clear all elements from the LinkedList list.clear(); // Check if the LinkedList is empty boolean isEmpty = list.isEmpty(); System.out.println("LinkedList is empty: " + isEmpty); } }
This example demonstrates creating a LinkedList
, adding elements to it, accessing elements, getting the size, removing elements, checking if an element exists, clearing the LinkedList
, and checking if it's empty. LinkedList
provides many more methods for manipulation and retrieval of elements, and its performance characteristics may be more suitable for certain use cases compared to ArrayList
.