Home > Tutorial > Java Linked List Sample Code

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:

package com.jcd.java.tutorials;


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
		linkedList.add("John");
		linkedList.add("Fred");
		linkedList.add("Jill");
		linkedList.add("Sean");
		
		System.out.println("\nlinkedList: "+linkedList);
		
		//Remove an element from the linked list
		linkedList.remove("Jill");
		
		System.out.println("\nlinkedList: "+linkedList);
		
		//Add an element to the linked list
		linkedList.add("Greg");
		
		System.out.println("\nlinkedList: "+linkedList);
		
		//Add an element to the first position of linked list
		linkedList.addFirst("Albert");
		
		//Duplicates are allowed so let's add a second John
		linkedList.add("John");
		
		System.out.println("\nlinkedList: "+linkedList);
		
		System.out.println("\nlinkedList Size: "+linkedList.size());
		
		//Check if a certain elements is in the linked list
		if(linkedList.contains("Fred"))
		{
			System.out.println("\nFound Fred in linkedList--> "+linkedList);
		}
		
		//Empty the linked list of all elements
		linkedList.clear();
		
		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



References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot