×

ArrayList VS Linked List

ArrayList VS Linked List

Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly.

Let’s see both the differences and similarities between ArrayList and LinkedList.

  LinkedList   ArrayList
Elements in the LinkedList are known as nodes, where each node consists of three parts -(1)reference to the previous element, (2)the actual value of the elements and (3) the address to the next element. In the ArrayList element is associated with the index. Because ArrayList is an index based data structure.
We can use LinkedList as ArrayList, Stack, Queue, Singly LinkedList and Doubly LinkedList,  once it is defined. We are unable to use ArrayList as a Stack or Queue.
It requires more memory if we compare it to the ArrayList. Because each node in the LinkedList holds data and reference to the previous and next element in the list. On the other hand, ArrayList requires less memory as compared to LinkedList. Because it holds only actual data and it’s index value.
Inserting and removing an element from the LinkedList is faster than the ArrayList. Because the shifting of the elements is not required after each insertion and deletion, in LinkedList, only the reference of previous and next elements are to be changed. Space and Time Complexity of LinkedList is O(n). Inserting and removing an element in the middle of the ArrayList is very slow. Because after every insertion or deletion, values in the ArrayList need to be shifted. Space and Time Complexity of Arraylist is O(1).
The elements in the LinkedList cannot be accessed randomly. We need to traverse from start to end to reach a particular element. In the ArrayList, the elements can be accessed randomly.
LinkedList is suitable to use for the insertion and deletion of the element than the retrieval. ArrayList is suitable to use more likely for the retrieval of the values than insertion and deletion.

Similarities between LinkedList And ArrayList:

  • LinkedList and ArrayList, both implements the List Interface.
  • Both are Cloneable and Serializable.
  • Both are non-synchronised.

Example code for LinkedList:

import java.util.*; 
public class LinkedList1 { 
 public static void main (String args []) { 
  LinkedList<String> al=new LinkedList<String> (); 
  al.add ("java"); 
  al.add ("python"); 
  al.add ("angular"); 
  al.add ("mongo db"); 
  al.addFirst ("R");
  Iterator<String> itr=ar.iterator (); 
  while (itr.hasNext ()){ 
   System.out.println (itr.next ()); 
  }   }  } 

Output:

R
java
python
angular
mongo db 

Example code for ArrayList:

import java.util.ArrayList;
 public class Arraylist {
        public static void main(String[] args)
        {
               // we will see how to add elements
               ArrayList al=new ArrayList();
               Object cloneList;
               al.add("Android");
               al.add("Java");
               al.add("Arrays");
               System.out.println("Size of arraylist:"+ al.size());//It will show the size               of the array
               System.out.println("Content of al:"+al);//It will show the contents of the array
               al.remove("Java");//It will remove java from the list
               System.out.println("Size of arraylist after deletion:"+al.size());
               System.out.println("Content of al:"+al);//prints content after deletion
               cloneList=al.clone();//It will clone the present element in the list
               System.out.println("Elements in the cloned list are:"+cloneList);
               al.clear();//It will clear the ArrayList
               System.out.println("Arraylist after clear:"+al);
        }
 } 

Output:

Size of arraylist:3
Content of al:[Android, Java, Arrays]
Size of arraylist after deletion:2
Content of al:[Android, Arrays]
Elements in the cloned list are:[Android, Arrays]
Arraylist after clear:[] 

ArrayList VS Vector

Both the ArrayList and Vector implements the List Interface. Both provide simple methods to store and get the object. But they are different in many aspects.

ArrayList Vector
ArrayList is introduced in JDK 1.2 release, so it is not a legacy class. Vector is a legacy class, i.e., it came along with the first version of JDK
To traverse the elements, ArrayList uses iterator interface. Vector uses the Enumeration interface. However, we can also use the Iterator interface to traverse the elements.
ArrayList is non-synchronized, that makes it fast. Vector is slow because it is synchronized. In a multithreading environment, it keeps the other threads in the runnable or non-runnable state until the current thread releases the lock over the object.
If there is no need for the thread-safe operation, ArrayList is a better choice as it gives better performance because of the concurrent processes. If there is a need to perform a thread-safe operation, Vector is the best choice.
Size of the ArrayList grows by half of its size when resized. Size of the Vector increases by double its size by default when resized.
ArrayList is fail-fast due to the iterator. If we modify the ArrayList structure, the iterator will throw ConcurrentModificationException error. But if we modify the vector over enumeration, it does not fail because iterator is fail-fast and enumeration is not.

Sample code to demonstrate the difference in fail-fast behavior of ArrayList and Vector:

import java.util.*;
class FailFastDemo {
       public static void main(String[] args)
    {
        //Initializing vector and storing the elements as array
        Vector<String> vector = new Vector<>(Arrays.asList("Java","Oracle","Spring"));
        //Using Enumeration for traversing
        Enumeration<String> vectorEnum = vector.elements();
        //Modifying the structure of vector
        while(vectorEnum.hasMoreElements()) {
            String value = vectorEnum.nextElement();
            if("Spring".equals(value)) {
                vector.add("Hibernate");
            }
            //printing the elements after modification
            System.out.println(value);
        }
        System.out.println("----------------");
        //Initializing ArrayList
        ArrayList<String> list = new ArrayList<>(Arrays.asList("Java","Oracle","Spring"));
        //Initializing iterator for traversing
        Iterator<String> listItr = list.iterator();
        //modifying the ArrayList
        while(listItr.hasNext()) {
            String value = listItr.next();
            if("Oracle".equals(value)) {
                list.add("SQL");
            }
            //printing the values
            System.out.println(value);
        }
    }
} 

Output:

Java
Oracle
Spring
Hibernate
----------------
Java
Oracle
Exception in thread "main" java.util.ConcurrentModificationException
       at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
       at java.util.ArrayList$Itr.next(Unknown Source)
       at StackJava.main(StackJava.java:33) 

Related Topics

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.