1. Introduction
In Java, LinkedList is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. In this guide, we will demonstrate how to add elements to a LinkedList in Java.
2. Program Steps
1. Create a LinkedList object.
2. Use the add method to add elements to the LinkedList.
3. Display the LinkedList to the console.
3. Code Program
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
// Step 1: Create a LinkedList object
LinkedList<String> animals = new LinkedList<>();
// Step 2: Use the add method to add elements to the LinkedList
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Step 3: Display the LinkedList to the console
System.out.println("LinkedList: " + animals);
}
}
Output:
LinkedList: [Dog, Cat, Horse]
4. Step By Step Explanation
Step 1: A LinkedList object named animals is created to store String elements.
Step 2: The add method of the LinkedList class is used to add String elements "Dog", "Cat", and "Horse" to the animals LinkedList.
Step 3: The contents of the animals LinkedList are displayed to the console, showing the elements that were added.