Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
}
like image 573
Ganesh Chowdhary Sadanala Avatar asked Jan 30 '26 10:01

Ganesh Chowdhary Sadanala


2 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.

like image 108
Joni Avatar answered Feb 01 '26 00:02

Joni


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.

like image 28
Tmrd993 Avatar answered Feb 01 '26 02:02

Tmrd993



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!