rndapology
rndapology

Reputation: 152

What to do when .equals() can't be set correctly?

I'm trying to use the excellent JGraphT library to write a Scrabble program in Java as practice with directed acyclic graphs and Java.

So, my edges are going to be letters and the vertices bitsets the size of the alphabet. Essentially, you traverse the graph letter by letter and check the bitset you're at to see what letters form a word if appended to the arc of letters you've followed from the root node.

I get that, but what worries me is this from the JGraphT Javadoc:

This method creates the new edge e using this graph's EdgeFactory. For the new edge to be added e must not be equal to any other edge the graph (even if the graph allows edge-multiplicity). More formally, the graph must not contain any edge e2 such that e2.equals(e). If such e2 is found then the newly created edge e is abandoned, the method leaves this graph unchanged returns null.

My edges and nodes will never be unique except in the sense that references don't match. So, my question is what would a Java programmer do here?

Upvotes: 1

Views: 161

Answers (1)

Christian Semrau
Christian Semrau

Reputation: 9013

The vertices already have an identity defined by the bits set in the BitSet, so you can use the BitSet itself for the vertices.

An edge should normally carry information about the vertices it starts and ends in, so I suggest an Edge class which contains the start BitSet, the end BitSet, and the edge Letter.

If no two edges exist between two vertices (i.e. edge-multiplicity is disallowed), then you can define equals and hashcode in the Edge class as testing for equality of start and end, ignoring the letter. If the letter of an edge is important because you might have multiple edges with equal start and end, you need a proper equality of letters between nodes.

Upvotes: 1

Related Questions