Java.util - SPLessons

Java.util LinkedList

Home > Lesson > Chapter 11
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java.util LinkedList

Java.util LinkedList

shape Description

Java LinkedList class utilizes doubly connected rundown to save the components. It expands the AbstractList class and executes List, Deque interfaces. Following is the declaration for the class. [java]public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable[/java]

shape Methods

The following are the various regular methods of the class.
Methods Description
void add(int index, Object item) To add an item.
boolean add(Object item) To add the value at end.
boolean addAll(Collection c) It includes every one of the components of the predefined gathering c to the rundown.
Object clone() To get the copy of an elenent.
E pop() To pops a component from the stack.

shape Example

The following is an example. LinkedListExample.java [java]import java.util.*; public class LinkedListExample { public static void main(String args[]) { /* Linked List Declaration */ LinkedList<String> linkedlist = new LinkedList<String>(); /*add(String Element) is used for adding * the elements to the linked list*/ linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2"); /*Display Linked List Content*/ System.out.println("Linked List Content: " +linkedlist); /*Add First and Last Element*/ linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist); /*This is how to get and set Values*/ Object firstvar = linkedlist.get(0); System.out.println("First element: " +firstvar); linkedlist.set(0, "Changed first item"); Object firstvar2 = linkedlist.get(0); System.out.println("First element after update by set method: " +firstvar2); /*Remove first and last element*/ linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); /* Add to a Position and remove from a position*/ linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); } }[/java] Output:Now compile the code result will be as follows. [java]Linked List Content: [Item1, Item5, Item3, Item6, Item2] LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6, Item2, Last Item] First element: First Item First element after update by set method: Changed first item LinkedList after deletion of first and last element: [Item1, Item5, Item3, Item6, Item2] Final Content: [Newly added item, Item1, Item3, Item6, Item2][/java]

Summary

shape Key Points

  • The void clear() is the method used to remove an elements.
  • The Object get(int index) method is used to give back the thing of the predefined record from the rundown.
  • The int size() to give back the quantity of components of the rundown.