Difference between ArrayList and HashSet in Java

JavaObject Oriented ProgrammingProgramming

HashSet and ArrayList both are some of the most important classes of the Java Collection framework.

The following are the important differences between ArrayList and HashSet.

Sr. No.KeyArrayListHashSet
1ImplementationArrayList is the implementation of the list interface.HashSet on the other hand is the implementation of a set interface.
2Internal implementationArrayList internally implements array for its implementation.HashSet internally uses Hashmap for its implementation.
3Order of elementsArrayList maintains the insertion order i.e order of the object in which they are inserted.HashSet is an unordered collection and doesn't maintain any order.
4DuplicatesArrayList allows duplicate values in its collection.On other hand duplicate elements are not allowed in Hashset.
5Index performanceArrayList uses index for its performance i.e its index based one can retrieve object by calling get(index) or remove objects by calling remove(index)HashSet is completely based on object also it doesn't provide get() method.
6Null AllowedAny number of null value can be inserted in arraylist without any restriction.On other hand Hashset allows only one null value in its collection,after which no null value is allowed to be added.

Example of ArrayList vs Hashset

JavaTester.java

 Live Demo

import java.io.*;
import java.util.*;
public class JavaTester {
   public static void main(String[] args) throws IOException{
      int n = 5;
      List<Integer> al = new ArrayList<>(n);
      for (int i = 1; i <= n; i++) {
         al.add(i);
      }
      System.out.println(al);
      al.remove(3);
      System.out.println(al);
      for (int i = 0; i < al.size(); i++) {
         System.out.print(al.get(i) + " ");
      }
   }
}

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

Example

JavaTester.java

import java.util.HashSet;
import java.util.Set;
public class JavaTester {
   public static void main(String[] args){
      Set<Integer> hs = new HashSet<>();
      hs.add(1);
      hs.add(2);
      hs.add(3);
      hs.add(4);
      hs.add(4);
      for (Integer temp : hs) {
         System.out.print(temp + " ");
      }
   }
}

Output

1 2 3 4
raja
Published on 18-Sep-2019 15:05:45
Advertisements