Idiomatic implementation of equals and hashCode from a Java class

The DefaultEdge class only has protected getSource and getTarget methods that return source and target fields from its superclass. There’s no setter method and no constructor that accepts source and target.

I want to override equals and hashCode and resorted to a regular class that extends DefaultEdge calling its default constructor, and used the getter methods in my overridden equals and hashCode. It works, but it would be nice to be able to make the data class do this work. Is that possible?

You could try a dataclass with the primary constructor overriding those vals to make them public like this:

data class MyEdge(public override val source: XX, public override val target: XX) : DefaultEdge(...)

The only constructor DefaultEdge has is the default no-arg, so what’s the ellipsis for?

1 Like

I figured that maybe default edge takes in something else sorry. The ellipsis are just to tell you to pass in whatever arguments you need here if any arguments are needed (i.e. they’re just a placeholder), but yeah other than that the code itself should hopefully work.

That solution would create new fields used by the overriding getters. The JGraphT implementation accesses the original fields (which are package-private) directly, so you risk that the two fields are going to come out of sync.

As for the original question, you are actually not allowed to define equals/hashCode the way you are trying to do. According to the user guide:

Note that when overriding equals / hashCode for an edge class, it is incorrect to incorporate the edge source/target into the operations; the edge identity is always independent of its connectivity.