Java LinkedList push() method
Syntax and Examples

Introduction

The push() method in Java's LinkedList class is a convenient way to add an element at the beginning of the list. Think of it like adding something to the front of a queue or inserting at index 0, but specifically designed for Linked Lists. It efficiently inserts the new element without shifting existing elements, which can be slower with arrays.

Syntax

public void push(E e)

Parameters

Parameter Description
e The element to be inserted at the beginning of the list. This can be any object of type E, where E is the generic type of the LinkedList (e.g., String, Integer).

Return Value

The push() method returns void. It doesn't return any value; it directly modifies the LinkedList by adding the element.

Examples

Example 1: Adding a String to the Beginning

This example demonstrates how to use push() to add a string at the beginning of a LinkedList. We create an empty LinkedList, push a string onto it, and then print the list to verify that the element has been inserted correctly.

import java.util.LinkedList;

public class PushExample1 {
    public static void main(String[] args) {
        LinkedList<String> myList = new LinkedList<>();
        myList.push("Hello");
        System.out.println(myList);  // Output: [Hello]
    }
}
[Hello]

Explanation: We create a LinkedList of Strings. The push() method adds "Hello" to the front, making it the first element in the list. The output confirms this.

Example 2: Adding Integers

This example showcases adding integers using the push() method.

import java.util.LinkedList;

public class PushExample2 {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();
        numbers.push(10);
        numbers.push(5);
        numbers.push(20);
        System.out.println(numbers); // Output: [20, 5, 10]
    }
}
[20, 5, 10]

Explanation: We create a LinkedList of Integers. Each call to push() inserts the integer at the beginning of the list. Notice that elements are added in reverse order of how they were pushed.

Example 3: Adding Different Data Types

This example illustrates adding a mix of data types (String and Integer) to a LinkedList. It's important to note that if you want to add different types, your list should be declared as using the object class Object.

import java.util.LinkedList;

public class PushExample3 {
    public static void main(String[] args) {
        LinkedList<Object> mixedList = new LinkedList<>();
        mixedList.push("Hello");
        mixedList.push(10);
        System.out.println(mixedList); // Output: [10, Hello]
    }
}
[10, Hello]

Explanation: We create a LinkedList that can store objects of type Object. This allows us to add both a String and an Integer. The elements are inserted at the beginning in the order they're pushed.