Java LinkedList push(E e) Method Example

In our previous article we have learnt article we have learnt about addFirst() method of java.util.LinkedList class which will inserts the specified element at the first of the list. push() method also does the same thing as addFirst(). 

Signature

public void push(E e)

This method appends the specified element to the beginning of this list.e is the element which will be appended.

Example

The following example shows the usage of java.util.LinkedList.push(e) method.

import java.util.LinkedList;

public class PushMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the linkedlist
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		
		//adding new element using push() 
		l.push("Element4");
		
		//Printing the elements of the list
		System.out.println("Elements of the list");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

Elements of the list
Element4
Element1
Element2
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *