LinkedList is a doubly-linked list implementation of the List and Deque interfaces. LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, LinkedList can be searched forward and backward but the time it takes to traverse the list is directly proportional to the size of the list.
Important Methods
- boolean add(E e)
Appends the specified element to the end of this list. - void add(int index, E element)
Inserts the specified element at the specified position in this list. - void clear()
Removes all of the elements from this list. - boolean contains(Object o)
Returns true if this list contains the specified element. - Iterator<E> descendingIterator()
Returns an iterator over the elements in this deque in reverse sequential order. - E get(int index)
Returns the element at the specified position in this list. - int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. - int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. - E peek()
Retrieves, but does not remove, the head (first element) of this list. - E poll()
Retrieves and removes the head (first element) of this list. - E remove()
Retrieves and removes the head (first element) of this list. - E remove(int index)
Removes the element at the specified position in this list. - boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present. - boolean removeLastOccurrence(Object o)
Removes the last occurrence of the specified element in this list (when traversing the list from head to tail). - int size()
Returns the number of elements in this list.
Example:
import java.util.*; public class LinkedListExample { public static void main(String args[]) { /* Linked List Declaration */ LinkedList<String> linkedlist = new LinkedList<String>(); /* add the elements to the linked list*/ linkedlist.add("Item1"); linkedlist.add("Item5"); /* Display Linked List Content*/ System.out.println("Linked List Content: " +linkedlist); /* Add First and Last Element*/ linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); /* Get and set Values*/ Object firstvar = linkedlist.get(0); linkedlist.set(0, "Changed first item"); /* Using Iterator*/ Iterator i = linkedlist.iterator(); while (i.hasNext()) { System.out.println(i.next()); } /*Remove first and last element*/ linkedlist.removeFirst(); linkedlist.removeLast(); } }