1.

ArrayList vs LinkedList in Java

Answer»

ArrayList and LinkedList are very important lists in Java. While the ArrayList implements a DYNAMIC array, the LinkedList implements a doubly linked list.

Some of the differences between Arraylist and LinkedList are given as follows:

  1. It is easier and much faster to insert elements in LinkedList as compared to ArrayList. The time complexity for INSERTION in ArrayList is O(n) in WORST case while it is O(1) in LinkedList.
  2. Deletion of elements is also easier in LinkedList as compared to ArrayList. However, the time complexity for deletion in ArrayList and LinkedList is O(n) in worst case.
  3. The time required to find if an element is available in both ArrayList and LinkedList is O(n) in the worst case. But binary search can be used on a sorted ArrayList to reduce this time to O(log n).
  4. There is more memory overhead in LinkedList as compared to ArrayList. This is because in LinkedList each node contains the data and address of the previous and next nodes while in ArrayList each index contains the data only.

A program that demonstrates ArrayList in Java is given as follows:

import java.util.ArrayList; public class ArrayListDemo {    public static void main(String[] args)    {        ArrayList&LT;String> al= new ArrayList<String>();        al.add("Apple");        al.add("Orange");        al.add("Guava");        al.add("MANGO");        al.add("Peach");        System.out.println(al);        al.remove(2);        System.out.println(al);        if (al.contains("Apple"))            System.out.println("Apple found in ArrayList");        else            System.out.println("Apple not found in ArrayList");    } }

The output of the above program is as follows:

[Apple, Orange, Guava, Mango, Peach] [Apple, Orange, Mango, Peach] Apple found in ArrayList

A program that demonstrates LinkedList in Java is given as follows:

import java.util.LinkedList; public class LinkedListDemo {    public static void main(String[] args)    {        LinkedList l = new LinkedList();        l.add("Apple");        l.add("Orange");        l.add("Guava");        l.add("Mango");        l.add("Peach");        System.out.println(l);        l.remove(0);        System.out.println(l);        if (l.contains("Apple"))            System.out.println("Apple found in LinkedList");        else            System.out.println("Apple not found in LinkedList");    } }

The output of the above program is as follows:

[Apple, Orange, Guava, Mango, Peach] [Orange, Guava, Mango, Peach] Apple not found in LinkedList


Discussion

No Comment Found