I understand it's possible, I just don't understand how. From what I can tell, if a class overrides the hashCode() and equals() methods to consider specified data members, references that instantiate that class will be given the same hash value as long as the specified data members they hold are the same. I have a feeling this is where I'm wrong, can anyone cite me an example of a hashCode() comparison returning true while a equals() method returns false on the same set of references? I apologize in advance if this is a repeat question, tried looking for a similar question to no avail.
Asked
Active
Viewed 278 times
1
-
1`String a = "FB", b = "Ea"; System.out.println(a.hashCode() == b.hashCode()); System.out.println(a.equals(b));` – Elliott Frisch Feb 08 '19 at 03:26
-
3The duplicate question I linked to contains some example from String. But even without knowing what they are, you could logically deduce that there _must_ be conflicts within String. After all, there are an infinite number of strings (one "small" but infinite subset of them is {"a", "aa", "aaa"...}), but a finite number of hashcodes (2^32), so clearly there must be some duplicates. – yshavit Feb 08 '19 at 03:28
-
Is this problem specific to strings? With strings, this collision makes since considering the finite hashcodes but I'm having a difficult time extrapolating this to say integers. Edit: I guess all you'd have to do give an integer a value beyond 2^32? Although an integer cannot store that high, maybe other non primitive types can – Matthew S. Feb 08 '19 at 03:32
-
For Integer, there won't be any collisions. The JavaDocs specify [`Integer#hashCode`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#hashCode--)'s behavior, and it's just to return the int value -- so you're right that there won't be a collision. Other number types, like Long and Double, _will_ have collisions. The hashCode contract doesn't specify that there _have_ to be collisions for any given class, just that there may be. Again, a though experiment: a one-value enum only has one instance, so by definition it can't have any collisions. – yshavit Feb 08 '19 at 03:43
-
"*if a class overrides the hashCode() and equals() methods to consider specified data members, references that instantiate that class will be given the same hash value as long as the specified data members they hold are the same*" -- true, but irrelevant. That's an argument for objects that compare equal having the same hash code, but you've asked about the opposite way around. If equal objects have the same hash code, that does not mean that unequal objects do not also have the same hash code. – John Bollinger Feb 08 '19 at 04:04
-
Why do you need an example? It happens all the time. That's the whole point of hash-codes: to map a large domain into a small range. `Integer` and friends are the exceptions, not the norm. – user207421 Feb 08 '19 at 05:45