I know that we prefer ArrayList
over HashSet
when we need to store duplicates, and HashSet
uses hashCode()
function to calculate an index for each element in its array.
So, this means if we want to store a single element, then ArrayList
should take less time than HashSet
. Please correct me if I am wrong anywhere.
But when I am checking performance through code I am getting different behavior.
Case 1:
import java.util.*;
class HashsetVSArraylist
{
public static void main(String args[])
{
ArrayList<Integer> a1=new ArrayList<Integer>();
long nanos = System.nanoTime();
a1.add(1);
System.out.println("ArrayList Time:"+(System.nanoTime()-nanos)+"ns");
HashSet<Integer> h1=new HashSet<Integer>();
nanos = System.nanoTime();
h1.add(2);
System.out.println("HashSet Insertion Time:"+(System.nanoTime()-nanos)+"ns");
}
}
Output:
ArrayList Time:495087ns
HashSet Insertion Time:21757ns
Case 2:
import java.util.*;
class HashsetVSArraylist
{
public static void main(String args[])
{
HashSet<Integer> h1=new HashSet<Integer>();
long nanos = System.nanoTime();
h1.add(2);
System.out.println("HashSet Insertion Time:"+(System.nanoTime()-nanos)+"ns");
ArrayList<Integer> a1=new ArrayList<Integer>();
nanos = System.nanoTime();
a1.add(1);
System.out.println("ArrayList Time:"+(System.nanoTime()-nanos)+"ns");
}
}
Output:
HashSet Insertion Time:582527ns
ArrayList Time:21758ns
Now, I assume HashSet
should take more time for insertion of a single element. But, in both cases behavior is different...less time is taken for the data structure which comes second in the code. Also, behavior changes when the number of elements inserted is more than 1000.
Please explain what is happening.