Using LinkedList (Collection)
by, 11-13-2011 at 12:40 PM (1153 Views)
LinkedList is a special type of List which is very useful in certain scenarios. Some important facts about LinkedList are:
- It is not synchronized
- It does not use array internally for storage
- It uses pointers internally to point to next node
- It implements Cloneable, List and Serializable interfaces
LinkedList is preferred when you know that you have to add and delete data from the start or from middle of the list. It perform addition and deletion efficiently because the data is in nodes and only pointers are to be changed in case of addition or deletion. But on the other hand, getting an element from a specified position is slow as LinkedList does not use array internally.
In the example below, we created a LinkedList and added 3 objects to it. We then added a 4th object at the first index using addFirst() method. This will add the new node to the first place and only few pointers are readjusted. This operation in LinkedList is very efficient as compared to ArrayList/Vector.
Output:Java Code:LinkedList linkedList = new LinkedList(); linkedList.add("Java"); linkedList.add("Pascal"); linkedList.add("C+"); linkedList.addFirst("Python"); Iterator it = linkedList.iterator(); while(it.hasNext()) System.out.println(it.next());
Similarly removing element is very efficient as no shifting is required as in Vector/ArrayList.