LinkedList

Java LinkedList is a doubly linked list implementation of the List and Deque interfaces. The LinkedList class implements all the optional operations defined by the List and allows all elements to be added to it including null elements.

The LinkedList class behaves exactly like what is expected from the doubly linked list.

Get operation using index will fetch the element either from the start of the linked list or from the end of the linked list depending upon which is closer to the specified index.

The LinkedList implementation is not synchronized. That means if there multiple threads trying to modify the LinkedList object simultaneously, the code must take care of the synchronization explicitly. That could be either done by synchronizing the linked list object, or you can get the synchronized list object from the existing LinkedList object using synchronizedList method of the Collections class as given below.

List list = Collections.synchronizedList(existingLinkedListObject);

The Iterator and ListIterator objects can be obtained from the LinkedList in order to iterate over the elements of the LinkedList. The Iterator and ListIterator objects returned by the LinkedList class are fail-fast in nature. That means if the LinkedList object is modified structurally (except through add or remove methods of the Iterator) after the Iterator or ListIterator is obtained from the LinkedList, it will throw ConcurrentModificationException.

Below given are some of the important methods of the LinkedList class.
1) The add method is used to add the elements to the LinkedList. The add method can also be used to insert the element at the specified index of the LinkedList.
2) The set method is used to replace the element at the specified index of the LinkedList.
3) The clear method removes all the elements from the LinkedList.
4) The contains method is used to check if the element exists in the LinkedList.
5) The getFirst and getLast methods returns the first and last element of the LinkedList respectively.
6) The size method returns the length or the size of the LinkedList.
7) The iterator and listIterator method returns the Iterator and ListIterator objects respectively which can be used to iterate over the elements of the LinkedList.

Below given are some of the Java LinkedList examples which shows how to use LinkedList in Java.

Java LinkedList Examples

Join 1000+ fellow learners! Enter your email address below: