LinkedList:
- LinkedList maintains insertion order of elements as it is implementing Queue interface.
- If we create object for LinkedList and with LinkedList reference variable, we can access complete functionality of Queue, List and Deque.
import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.add(100);
list.add(200);
System.out.println("List : "+list);
list.addFirst(111);
list.addLast(222);
System.out.println("List : "+list);
System.out.println("Peek : "+list.peek()); //Returns top element but not remove
System.out.println("After peek List : "+list);
System.out.println("Poll : "+list.poll()); //Returns top element & remove
System.out.println("After poll List : "+list);
}
}
Note : If we collect LinkedList object address into a particular implemented interface type, we cannot access all the interfaces functionality.
import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
Queue q = new LinkedList();
q.add(100);
q.add(200);
System.out.println("Queue : "+q);
System.out.println("Peek : "+q.peek());
q.addFirst(111); // Error : not specified in Queue
System.out.println("Queue : "+q);
}
}
Output this following code:
import java.util.*;
class LinkedListDemo{
public static void main(String[] args) {
LinkedList l = new LinkedList();
for(int i=10 ; i<=100 ; i+=10){
l.add(new Integer(i));
}
System.out.println("List : "+l);
for(int i=0 ; i<l.size() ; i++){
System.out.println("Poll : "+l.poll());
}
}
}