Reputation: 1278
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
}
}
Upvotes: 3
Views: 3198
Reputation: 2608
It would follow its default behaviour - it would first check if there is any existing entry (using hashCode() and equals() ) and if found, it would replace it and if not, it would insert it.
Note that the hashCode()
and equals()
method invocations will eventually get invoked on the object-entry - in this case the ArrayList object itself (ArrayList inturn inherits the methods from AbstractList ).
PS : It appears HashSet is implemented internally as a HashMap !
Upvotes: 0
Reputation: 76
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.
Upvotes: 0
Reputation: 78945
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
.
Upvotes: 1
Reputation: 111219
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.
Upvotes: 7
Reputation: 61
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.
Upvotes: 1