Write a Java program to Add an item to the tail of LinkedList


The code demonstrates how to use the offer method of LinkedList in Java to add an item at the end of the list, also known as the tail.

In the AddItem_Tail class, a LinkedList object named list is created without specifying a type parameter, allowing it to hold items of any type. Several items of different types, including 18, "Apple", 54.78, 'T', and true, are added to the list using the add method.

The System.out.println statements are used to print the items in the list before and after adding an item at the tail. The offer method is then used to add the item "Cherry" at the end of the list. The offer method returns true if the item was successfully added to the end of the list, and false otherwise.

After adding the item at the tail using offer, the updated list is printed using the System.out.println statement. Note that offer is equivalent to add and can be used interchangeably to add an item at the end of the list.

Source Code

import java.util.LinkedList;
public class AddItem_Tail
{
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.add(18);
		list.add("Apple");
		list.add(54.78);
		list.add('T');
		list.add(true);
 
		System.out.println("LinkedList Items : " + list);	
		// Add an element at tail of LinkedList.
		list.offer("Cherry");
 
		System.out.println("LinkedList Items : " + list);
	}
}

Output

LinkedList Items : [18, Apple, 54.78, T, true]
LinkedList Items : [18, Apple, 54.78, T, true, Cherry]

Example Programs