Java Linked List Sample Code

The Java LinkedList is a double linked list implementation of the List and Deque interfaces. The LinkedList collection class implements all optional list operations and permits all elements. Because the LinkedList is not synchronized it is not thread safe. Duplicate elements are allowed in a LinkedList as you will see in the sample code below.

Class Name Method Parameters Return Type Exceptions
LinkedList add() element boolean none
LinkedList addFirst() element void none
LinkedList clear() none void none
LinkedList contains() element boolean none
LinkedList remove() element boolean none
LinkedList size() none int none

Java Linked List Source Code:


import java.util.LinkedList;

public class JavaLinkedList 

	public static void main(String[] args) 

		//Create an empty linked list object
		LinkedList<String> linkedList = new LinkedList<String>();
		//Add elements to the linked list
		System.out.println("\nlinkedList: "+linkedList);
		//Remove an element from the linked list
		System.out.println("\nlinkedList: "+linkedList);
		//Add an element to the linked list
		System.out.println("\nlinkedList: "+linkedList);
		//Add an element to the first position of linked list
		//Duplicates are allowed so let's add a second John
		System.out.println("\nlinkedList: "+linkedList);
		System.out.println("\nlinkedList Size: "+linkedList.size());
		//Check if a certain elements is in the linked list
			System.out.println("\nFound Fred in linkedList--> "+linkedList);
		//Empty the linked list of all elements
		System.out.println("\nlinkedList: "+linkedList);
		System.out.println("\nlinkedList Size: "+linkedList.size());



Java Linked List Output:

linkedList: [John, Fred, Jill, Sean]

linkedList: [John, Fred, Sean]

linkedList: [John, Fred, Sean, Greg]

linkedList: [Albert, John, Fred, Sean, Greg, John]

linkedList Size: 6

Found Fred in linkedList--> [Albert, John, Fred, Sean, Greg, John]

linkedList: []

linkedList Size: 0


Add a Comment

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