import java.util.*;
public class ArrayListDemo
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of ArrayList: "+al.size());
// add element to the ArrayList
al.add("Mango");
al.add("Banana");
al.add("Orange");
al.add("Papaya");
al.add("Mango");
System.out.println("ArrayList elements after addition: "+al);
System.out.println("Size of ArrayList:"+al.size());
// Remove the 5th indes elemenrt
al.remove(4);
System.out.println("ArrayList elements after deletion: "+al);
//Remove Banana
al.remove("Banana");
System.out.println("ArrayList elements after deletion: "+al);
System.out.println("Size of ArrayList after deletion: "+al.size());
//Retriving 2nd index element
String al1 = (String)(al.get(2));
System.out.println("The element at 2nd index is: "+al1);
}
}
import java.util.*;
public class LinkedListDemo
{
public static void main(String args[])
{
// create a linked list
LinkedList<String> ll = new LinkedList<String>();
System.out.println("Initial size of LinkedList: "+ll.size());
// add elements to the linked list
ll.add("Java");
ll.add("C++");
ll.add("PHP");
ll.add("DBMS");
ll.add("CSS");
ll.addLast("JavaScript");
ll.addFirst("HTML");
System.out.println("Element of LinkedList: " + ll);
System.out.println("Size of LinkedList after addition: "+ll.size());
// remove elements from the linked list
ll.remove("PHP");
ll.remove(4);
System.out.println("Element of LinkedList after deletion: " + ll);
System.out.println("Size of the LinkedList after deletion: "+ll.size());
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
System.out.println("Size of the LinkedList after deletion: "+ll.size());
//Retriving First and Last element
System.out.println("Fisrt element of LinkedList: "+ll.getFirst());
System.out.println("Last element of LinkedList: "+ll.getLast());
Iterator<String> itr = ll.iterator();
while(itr.hasNext())
{
System.out.print(itr.next()+", ");
}
}
}
ArrayList | LinkedList |
---|---|
Serach operation in ArrayList is fast compared to LinkedList. | Searching in LinkedList is slow. |
ArrayList cannot be iterated in reverse order. | LinkedList can be iterated in reverse direction by using descendingIterator(). |
Insertion and deletion is slow is compared to LinkedList. | Insertion and deletion are easy and fast in LinkedList. |
ArrayList works as the list, because it implements List only. | LinkedList implements both List and Deque interface. |
ArrayList maintains only index and element data. | LinkedList maintais the element data and two pointers for neighbor nodes. |