Monday, December 30, 2024
Google search engine
HomeLanguagesJavaDifference Between ArrayList and HashMap in Java

Difference Between ArrayList and HashMap in Java

ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and in order to access a value, one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. 

Hashing is a technique of converting a large String to a small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles.

Here we will proceed by discussing common features shared among them. Then we will discuss differences between them by performing sets of operations over both of them in a single Java program and perceiving the differences between the outputs.

First, let us discuss the Similarities Between ArrayList and HashMap in Java

  • The ArrayList and HashMap, both are not synchronized. So in order to use them in the multi-threading environment, it needs to be first synchronized.
  • Both ArrayList and HashMap allow null. ArrayList allows null Values and HashMap allows null key and values
  • Both ArrayList and HashMap allow duplicates, ArrayList allows duplicate elements, and HashMap allows duplicate values
  • Both ArrayList and HashMap can be traversed through Iterator in Java.
  • Both Somewhere use an array, ArrayList is backed by an array, and HashMap is also internally implemented by Array
  • Both use get() method, the ArrayList.get() method works based on an index, and HashMap.get() method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched so both provides constant-time performance.

Java Collection

By far we get some clarity from the media provided above and now we will be performing sets of operations over them in order to perceive real differences via concluding differences in outputs over the same operation which increases our intellect in understanding the differences between ArrayList and HashMap.

  • Hierarchy alongside syntax
  • Maintenance of insertion order
  • Memory Consumption
  • Duplicates elements handling
  • Ease of fetching an element
  • Null element storage

Differences Between ArrayList and HashMap in Java

1. Hierarchy alongside syntax

Interface Implemented: ArrayList implements List Interface while HashMap is the implementation of Map interface.

Syntax: Declaration of ArrayList Class

public class ArrayList 
extends AbstractList 
implements List, RandomAccess, Cloneable, Serializable

Syntax: Declaration of HashMap Class

public class HashMap 
extends AbstractMap 
implements Map, Cloneable, Serializable  

2. Maintenance of the Insertion Order

ArrayList maintains the insertion order while HashMap does not maintain the insertion order which means ArrayList returns the list items in the same order while HashMap doesn’t maintain any order so returned key-values pairs any kind of order.

Example:

Java




// Java Program to illustrate Maintenance of Insertion Order
// in ArrayList vs HashMap 
  
// Importing all utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Creating ArrayList of string type
        ArrayList<String> list = new ArrayList<String>();
  
        // Adding object in ArrayList
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
  
        // Invoking ArrayList object
        System.out.println("ArrayList: " + list);
  
        // Creating HashMap
        HashMap<Integer, String> hm
            = new HashMap<Integer, String>();
  
        // Adding object in HashMap object created above
        // using put() method
        hm.put(1, "A");
        hm.put(2, "B");
        hm.put(3, "C");
        hm.put(4, "D");
  
        // Invoking HashMap object
        // It might or might not display elements
        // in the insertion order
        System.out.print("Hash
                         Map: " + hm);
    }
}


Output: 

ArrayList: [A, B, C, D]
HashMap: {1=A, 2=B, 3=C, 4=D}

 

3. Memory Consumption

ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively.

Syntax: ArrayList

list.add("A");
// String value is stored in ArrayList

Syntax: HashMap

hm.put(1, "A");
// Two String values stored
// as the key value pair in HashMap

4. Duplicates element handling 

ArrayList allows duplicate elements while HashMap doesn’t allow duplicate keys but does allow duplicate values.

Example

Java




// Java Program to Illustrate Duplicate Elements Insertion
// in ArrayList vs HashMap
  
// Importing utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Creating ArrayList of string type
        ArrayList<String> list = new ArrayList<String>();
  
        // Adding object in ArrayList
        list.add("A");
        list.add("B");
  
        // Add duplicates
        list.add("A");
        list.add("A");
  
        // Invoking ArrayList object
        System.out.println("ArrayList: " + list);
  
        // Creating HashMap
        HashMap<Integer, String> hm
            = new HashMap<Integer, String>();
  
        // Adding object in HashMap
        hm.put(1, "A");
        hm.put(2, "B");
  
        // Add duplicates key
        // Change value if index exist
        hm.put(3, "A");
        hm.put(3, "A");
  
        // Add duplicates values
        // allow duplicates value
        hm.put(4, "A");
        hm.put(5, "A");
  
        // Invoking HashMap object
        System.out.print("HashMap: " + hm);
    }
}


Output: 

ArrayList: [A, B, A, A]
HashMap: {1=A, 2=B, 3=A, 4=A, 5=A}

 

5. Ease of fetching an element

In ArrayList, an element can be fetched easily by specifying its index it. But in HashMap, the elements are fetched by their corresponding key. It means that the key must be remembered always. 

Note: ArrayList get(index) method always gives O(1) time complexity While HashMap get(key) can be O(1) in the best case and O(n) in the worst case time complexity.

Example

Java




// Java Program to Illustrate Ease of fetching an Element
// in ArrayList vs HashMap
  
// Importing all utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // main driver method
    public static void main(String args[])
    {
        // Creating ArrayList of string type
        ArrayList<String> list = new ArrayList<String>();
  
        // Adding object in ArrayList
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
  
        // Invoking ArrayList object
        System.out.println("First Element of ArrayList: "
                           + list.get(0));
        System.out.println("Third Element of ArrayList: "
                           + list.get(2));
  
        // Creating HashMap
        // Declaring object of integer and string type
        HashMap<Integer, String> hm
            = new HashMap<Integer, String>();
  
        // Adding object in HashMap
        hm.put(1, "A");
        hm.put(2, "B");
        hm.put(3, "C");
        hm.put(4, "D");
  
        // Invoking HashMap object
        System.out.println("HashMap value at Key 1: "
                           + hm.get(1));
        System.out.println("HashMap value at Key 3: "
                           + hm.get(3));
    }
}


Output: 

First Element of ArrayList: A
Third Element of ArrayList: C
HashMap value at Key 1: A
HashMap value at Key 3: C

 

6. Null element storage

In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number.

Example

Java




// Java Program to Illustrate Null Element Storage in
// Arraylist vs HashMap
  
// Importing all utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // main driver method
    public static void main(String args[])
    {
        // Creating ArrayList of string type
        ArrayList<String> list = new ArrayList<String>();
  
        // Adding object in ArrayList
        // using standard add() method
        list.add("A");
  
        // Adding first null value
        list.add(null);
        list.add("C");
  
        // Adding two null value again
        list.add(null);
        list.add(null);
  
        // Invoking ArrayList object
        System.out.println("ArrayList: " + list);
  
        // Creating HashMap
        // Declaring object of integer and string type
        HashMap<Integer, String> hm
            = new HashMap<Integer, String>();
  
        // Adding object in HashMap
        hm.put(1, "A");
        hm.put(2, "B");
  
        // add null key
        hm.put(null, "C");
  
        // Again adding null key
        // which replace value of first
        // insert null key value
        hm.put(null, null);
  
        // Adding second null value
        hm.put(3, null);
  
        // Printing the elements of Hashmap
        System.out.println("HashMap: " + hm);
    }
}


Output: 

ArrayList: [A, null, C, null, null]
HashMap: {null=null, 1=A, 2=B, 3=null}

 

So, let us figure out the differences between ArrayList and HashMap in a table:

ArrayList

HashMap

The java ArrayList implements List Interface 
 
The java HashMap implements Map interface 
 
ArrayList always maintain the insertion order of the elements 
 
HashMap does not maintain the insertion order.
ArrayList only stores value or element 
 
HashMap stores key and value pairs 
 
ArrayList can contain duplicate elements 
 
HashMap does not contain duplicate keys but contains duplicate values. 
 
We can have any number of null elements in ArrayList 
 
We can have only one null key and any number of null values in HashMap 
 
ArrayList get() method always gives an O(1) performance 
 
HashMap get()method can be O(1) in the best case and O(n) in the worst case 
 
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments