Using LinkedList (Collection)
5 December 2007LinkedList 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.
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());
Output:
Python Java Pascal C+
Similarly removing element is very efficient as no shifting is required as in Vector/ArrayList.
Related Posts:
- LinkedList (Generics)
- LinkedList - insertion/deletion
- More on Collection FrameWork
- Removing elements from a List
- Java performance Issues (III) - Garbage collection
- Sharing setUp() and tearDown() code for all tests - II
- Java Generics with legacy code (II)
- Java Generics with legacy code (I)
- Hibernate Filters - I
- Lazy associations – II
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Using LinkedList (Collection)