HashSet issue - equals and hashCode with work differently than I expected

I have the following code:

class IncidentTag:
     def __init__(self,tag):
        self.tag = tag
     def equals(self,obj):
        return self.tag.equals(obj.tag)
     def hashCode(self):
        return self.tag.hashCode()

from java.lang import String
from java.util import HashMap
from java.util import HashSet

tag1 = IncidentTag(String("email"))
tag1copy = IncidentTag(String("email"))
tag2 = IncidentTag(String("notemail"))

print tag1.equals(tag1copy)
print tag2.equals(tag2)

print "Now with HashSet:"

hSet = HashSet()
hSet.add(tag1)
hSet.add(tag2)

print hSet.contains(tag1)
print hSet.contains(tag2)
print hSet.contains(tag1copy)

Exit: 1 1 Now using HashSet: 1 1 0

However, I would expect the last line to be true (1). Is there something obvious that I'm missing.

(yes, I know that my equals method and hashcode methods do not account for some problems ... they are intentionally simple, but let me know if problems arise because of this problem)

+3
source share
3 answers

You should not use the Java-Style equals and hashCode methods, but instead Python equivalents __eq__and __hash__. Adding

def __hash__(self):
    return self.hashCode()
def __eq__(self, o):
    return self.equals(o)

. python, , hashCode equals() Jython. , Python Java.

"1".

+10

Java, true contains(). , Jython. , Java , , Python.

+1

Python, , Java equals() hashcode() .

  • , equals() hashcode().

This seems to be broken. HashSets are first going to use the hash code in the search to get a list that contains the corresponding object, and then go to the list to find the one that is equal. If your hash code does not fulfill the contract and they return different hash codes, then it will not find it in the hash set, even if they are equal () are comparable.

By default, Java Object.hashcode () will not return the same hash code for 2 objects. You must override it.

0
source

Source: https://habr.com/ru/post/1698650/


All Articles