LinkedList In Java

Earlier we have seen Arrays and ArrayList. In this post, we will see LinkedList in Java. LinkedList is a class in the Collection Framework. LinkedList class implements List and Deque interfaces. LinkedList class extends AbstractList class. Lets see some key points on LinkedList.

  • LinkedList class can hold duplicate elements in list.
  • LinkedList is used to create an empty linked list.
  • LinkedList class maintains insertion order.
  • LinkedList class is non synchronized.
  • In LinkedList class, manipulation is fast because shifting is not required when new element is inserted or deleted from the list.

Java LinkedList Example:

Output:

LinkedList using For loop:

Output:

LinkedList with Enhanced For Loop:

Output:

LinkedList using Iterator:

Methods for Java LinkedList:

  • int size(): It returns the number of elements in the list.
  • void clear(): It removes all of the elements from the list.
  • Object set(int index, Object element): It is used to replace an existing element in the list with a new element.
  • void add(int index, Object element): It inserts the element at the position ‘index’ in the list.
  • void addFirst(Object element): It inserts the element at the beginning of the list.
  • void addLast(Object element): It appends the element at the end of the list.
  • Object get(int index): It returns the element at the position ‘index’ in the list. It throws ‘IndexOutOfBoundsException’ if the index is out of range of the list.
  • Object getFirst(): It returns the first element of the Linked List.
  • Object getLast(): It returns the last element of the Linked List.
  • int indexOf(Object element): If element is found, it returns the index of the first occurrence of the element. Else, it returns -1.
  • int lastIndexOf(Object element): If element is found, it returns the index of the last occurrence of the element. Else, it returns -1.
  • Object remove(): It is used to remove and return the element from the head of the list.
  • Object remove(int index): It removes the element at the position ‘index’ in this list. It throws ‘NoSuchElementException’ if the list is empty.
  • Object removeLast(): It is used to remove and return the last element of the Linked List.
Must Read: Java Tutorial

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

Leave a Comment

Share via
Copy link
Powered by Social Snap