I've got this question twice on two different interviews and I'm kinda confused as each time I've heard different answer -> once that it's equals based and another time that it is hashcode based. So what's the truth?
Asked
Active
Viewed 47 times
0
-
2That's an ill-posed question. `HashSet` (at least in oracle's implementation) is backend by a `HashMap` which puts elements in buckets based on `hashCode` but uses `equals` for the `get` method. – Federico klez Culloca Nov 07 '22 at 07:54
-
Technically, I suppose I would answer "equals based". But how that equality is determined depends on the set implementation. A `HashSet` will first use `hashCode`, and then only consults `equals` if two objects give the same hash. Whereas a `TreeSet` determines equality via a `Comparator`, which may or may not be "consistent with equals". Ultimately, I agree with @Federico in that the question seems poor. – Slaw Nov 07 '22 at 07:56
-
1What does “xyz based” even mean in this context? Are those questioners assuming that the entire interface (or even the underlying concept) is build atop a single method? – Holger Nov 07 '22 at 11:02
-
It is **both** (for `java.util.HashSet`) – Mark Rotteveel Nov 07 '22 at 13:29
-
1I agree that this is an ill-posed question. Lurking beneath it though is a real issue: what equivalence function forms the basis for membership in the set? For `Set` in general there is no single answer. Particular implementations have different answers. For `HashSet` it's `equals`; for a set based on `IdentityHashMap` it's `==`, and for `TreeSet` it's `compare()==0`. – Stuart Marks Nov 07 '22 at 17:11