LinkedList is not most commonly used class for storing the values. The LinkedList class extends AbstractSequentialList and implements the List interface. It stores the data using linked-list data structure. This class has two constructors,
- With empty parameters – LinkedList() and
- With Collection object as the parameter – LinkedList (Collection c)
Some of the important features of this class is:
- It supports the duplicate elements insertion
- Similar to ArrayList, it maintains the insertion order
- LinkedList is not synchronized
- It doesn’t support the random access for retrieving the values
- It can be used as list, stack or queue.
One of the main drawback of using the linked list is that each element should have a pointer to the next and previous elements, It is extra overhead for each elements. This overhead is not with the ArrayList. The only time when LinkedList is better than ArrayList is that, when performing insertion or removal with the iterator which is more efficient than the ArrayList. In ArrayList every insertion or removal needs the copy of objects to new array.
LinkedList Example
package javabeat.net.core; import java.util.Iterator; import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { LinkedList<String> list = new LinkedList<String>(); list.add("Element 1"); list.add("Element 2"); list.add("Element 3"); list.add("Element 4"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Methods in LinkedList
The following are the methods defined in the LinkedlIst class. If you want to read more about each methods, please refer documentation.
- void add(int index, Object element)
- boolean add(Object obj)
- boolean addAll(Collection c)
- boolean addAll(int index, Collection c)
- void addFirst(Object obj)
- void addLast(Object obj)
- void clear()
- Object clone()
- boolean contains(Object obj)
- Object get(int index)
- Object getFirst()
- Object getLast()
- int indexOf(Object obj)
- int lastIndexOf(Object obj)
- ListIterator listIterator(int index)
- Object remove(int index)
- boolean remove(Object obj)
- Object removeFirst()
- Object removeLast()
- Object set(int index, Object element)
- int size()
- Object[] toArray()
- Object[] toArray(Object[] a)