LinkedList in Java

LinkedList in Java is doubly-linked list implementation of the List and Deque interfaces. LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue interfaces and permits null elements. It provides a linked-list data structure. LinkedList in Java is a generic class which has below declaration:

class LinkedList<E>

Here, E specifies the type of objects that the list will hold. LinkedList has the two constructors which are shown below.

Constructors:

LinkedList( )
LinkedList(Collection<? extends E> c)

The first constructor builds an empty linked list. The second constructor builds a linked list that is initialized with the elements of the collection c.

As LinkedList implements the Deque interface, the methods defined in Deque interface will be available in LinkedList class. For example, to add elements to the start of a list you can use addFirst( ) or offerFirst( ). To add elements to the end of the list, use addLast( ) or offerLast( ). To obtain the first element, you can use getFirst( ) or peekFirst( ). To obtain the last element, use getLast( ) or peekLast( ). To remove the first element, use removeFirst( ) or pollFirst( ). To remove the last element, use removeLast( ) or pollLast( ).

Following program demonstrates the LinkedList.

Example:

Output:

You can also learn about ArrayList at this tutorial ArrayList in Java.

Related posts

Leave a Comment