I'm implementing an A* algorithm in Java, and I'm using a TreeSet as an easy way of keeping the open list sorted. If you're not familiar with A*, it's basically a function to get the shortest path from A to B, and the open list is a list of nodes (in my case Tiles
) sorted based on their closeness to B.
My objects implements a compareTo()
function for sorting like so:
@Override
public int compareTo( Tile b )
{
return ( this.f< b.f) ? -1 : ( this.f> b.f) ? 1 : 0;
}
My problem comes when I try to add some tiles to the open list - TreeSet seems to use compareTo()
to check if the object is already there, rather than equals()
. As it's possible that two different Tiles
have the same f
value, the TreeSet thinks that the object already exists in the list and doesn't add it.
According to the docs (or at least, how I'm reading it), it should use equals
:
"Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2))." (emphasis mine).
How can I get the TreeSet to use equals()
when calling add()
or contains()
and compareTo()
for sorting? For info, my Tile
class doesn't override the equals()
function, so it should get the default return a == b
.
If what I'm trying to do isn't possible with TreeSet, what's the proper collection that I should be using?