LinkedList In Java | Java Tutorial

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

Sharing is caring.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Like This Post?

We have a lot more where that came from?

We only send really good stuff occasionally, promise.

Rajkumar SM

Leave a Comment

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

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on whatsapp

Recent Posts:

Scroll to Top
API Testing eBook

DOWNLOAD FOR FREE