Collection : LinkedList Example
This tutorial contains description of Collection LinkedList with example.
LinkedList :
LinkedList class implements the List interface. It is ordered by index
position. It is like ArrayList ,except that it provides concept of
doubly-linked.
It implements methods of List interface and concept of doubly-linked uses some
new methods for adding and removing from the beginning or end, which makes easy
to use it for Stack and Queue implementation.
Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but
it's a good choice when you need fast insertion and deletion
Example :
package collection; import java.util.LinkedList; class LinkedListExample { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<Integer>(); System.out.println("Initial size of LinkedList : " + list.size()); // Adding elements to the LinkedList list.add(111); list.add(222); list.add(333); list.add(1, 666); System.out.println("Size of LinkedList after adding elements : " + list.size()); System.out.println("Elements in LinkedList : " + list); // Removing elements list.remove(1); System.out.println("Size of LinkedList after removing element : " + list.size()); System.out.println("Elements in LinkedList : " + list); } }
Description : In this example we are creating LinkedList of
Integer as - LinkedList<Integer> list = new LinkedList<Integer>();
add() method is used here to add elements into list. For
calculating number of elements in list we are using size()
method.
remove() method is used here to delete elements from
list.
Output :
Initial size of LinkedList : 0 Size of LinkedList after adding elements : 4 Elements in LinkedList : [111, 666, 222, 333] Size of LinkedList after removing element : 3 Elements in LinkedList : [111, 222, 333]