FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Linked List Data Structures

Code Description:

Lists are similar to Arrays in how they store data sequentially. Linked Lists are special in that they are able to expand in size during run-time, unlike standard Arrays. Linked Lists are more efficient than Array Lists when you need to insert or remove elements at the beginning or end of the list.

Linked List Syntax:

LinkedList<String> linkedList = new LinkedList<String>();

Runnable Linked List Example Code:

import java.util.LinkedList;

public class Demo {

    public static void main(String[] args) {
		
        LinkedList<String> linkedList = new LinkedList<String>();
		
	linkedList.addFirst("Element1");
	linkedList.addLast("Element2");
	linkedList.addFirst("Element3");
	linkedList.add("Element4");
		
	for (String linkedListElement : linkedList) {
	    System.out.println(linkedListElement);
	}

    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

Linked List Output Image

Important Methods:

  • add() - adds a single element at the specified index to the list.
  • addAll() - adds all elements in a collection (array, another list, etc).
  • get() - retrieves the element at the specified index. Note that this is very inefficient. If needed to traverse a link list, try to use a Foreach loop rather than a For loop.
  • remove() - deletes the element at the specified index.
  • size() - returns the number of elements in the list.
  • clear() - removes all elements in the list.
  • addFirst() - adds an element to the head of the list.
  • addLast() - adds an element to the tail of the list.
  • getFirst() - retrieves the element at the head of the list.
  • getLast() - retrieves the element at the tail of the list.
  • removeFirst() - removes the element at the head of the list.
  • removeLast() - removes the element at the tail of the list.

Related Links:

For-each Loops Array Data Structures Array List Data Structures Stack Data Structures Queue Data Structures