LinkedList & its feature ::
1. LinkedList class is an important class of Collection framework.
2. LinkedList extends generic AbstractSequentialList.So the elements in LinkedList are stored in insertion order.
3. LinkedList implements generic List, generic Deque, Cloneable and java.io.Serializable interface.
4. LinkedList internally has a double LinkedList.Doubly LinkedList Node has three attributes generic item,addresee of previous node and address of next node.
1 2 3 4 5 6 7 8 9 10 11 |
private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } } |
5. LinkedList is unsynchronized i.e. it is not thread safe.But, it can be made synchronized explicitly like below
1 |
List<String> l = java.util.Collections.synchronizedList(new LinkedList<String>()); |
5. LinkedList can accept any element including multiple null values.
7. LinkedList uses Iterator interface to traverse the elements.While traversing the elements using iterator if the structure of the LinkedList is modified using add or remove method ,iterator will throw ConcurrentModificationException.So iterators for LinkedList are fail-fast.
Sample Program ::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.ai1tutorial.collection.LinkedList; import java.util.LinkedList; import java.util.Iterator; import java.util.List; public class LinkedListDemo { public static void main(String[] args) { List linkedList = new LinkedList<String>(); linkedList.add("Ajay"); linkedList.add("Kumar"); linkedList.add("Mohanty"); Iterator iterator = linkedList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } |
Output ::
1 2 3 |
Ajay Kumar Mohanty |
Now let us see an example of ConcurrentModificationException.In the below program while iterating the LinkedList,i am modifying the structure of the LinkedList by adding a new element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.ai1tutorial.collection.LinkedList; import java.util.LinkedList; import java.util.Iterator; import java.util.List; public class LinkedListDemo { public static void main(String[] args) { List<String> linkedList = new LinkedList<String>(); linkedList.add("Ajay"); linkedList.add("Kumar"); linkedList.add("Mohanty"); Iterator iterator = linkedList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); LinkedList.add("Jyoti"); } } } |
Output ::
1 2 3 4 5 |
Ajay Exception in thread "main" java.util.ConcurrentModificationException at java.util.LinkedList$Itr.checkForComodification(Unknown Source) at java.util.LinkedList$Itr.next(Unknown Source) at com.ai1tutorial.collection.LinkedList.LinkedListDemo.main(LinkedListDemo.java:16) |