How the ArrayList objects are stored inside a HashSet in Java?

Viewed 1578

Today I was doing a question and in that they have used a code similar to this. I am amazed to see this. I thought every HashSet stores the hash of an object and the answer would be 2. However, the answer to this 1. Could anyone explain what actually happens internally when I store HashSet of ArrayList of objects and why the answer is 1 instead of 2?

import java.io.*;
import java.util.*;

class Code {
    public static void main (String[] args) {
        
        HashSet<ArrayList<Integer>> set=new HashSet<>();
        ArrayList<Integer> list1=new ArrayList<>();
        ArrayList<Integer> list2=new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list2.add(1);
        list2.add(2);
        set.add(list1);
        set.add(list2);
        System.out.println(set.size()); // 1
    }
}
5 Answers

Two instances of List are considered "equal" if they have the same elements in the same order. So that means list1 and list2 are "equal". By the general contract of the hashCode method they must also have the same hash code

HashSet does not store duplicate items: if you give it two items that are equal it stores only the first one. So here it's storing list1 only.

The answer is 1 because both Lists contain the same elements. The hash code of an ArrayList is a function of the hash codes of all elements in the list. In your case, both lists contain the same elements which means they correspond to the same hash code.

HashSet implements the Set interface, backed by a hash table. Any implementation of Set simply discards the duplicate elements. Since both list1 and list2 are equal, set will discard list2 when you try to insert it into into set when set already has list1. Thus, the size of set remains 1.

Here both the list values are equal so there hashcode is also the same by the contract and hashset stores hash value of its object and doesn't contain duplicates so list1 is replaced with list2 and hence the size is 1.

Related