Note 7.6.2. Java Notes.
We not only want to make sure that the data type of a key can be compared (line 4); we also want to make sure that we can compare vertices to each other (line 5) in some of the algorithms for this chapter. This requires us to implement a
compareTo
method (lines 68–70). It returns the result of comparing the keys; a negative number if this.key
is less than other.key
, zero if they are equal, and positive if this.key
is greater than other.key
.In line 41, we return the neighbors as a Java
Set
. A set has the property that there are no duplicate elements. Sets are iterable, which means that we can use an extended for
loop to examine all of a vertex’s neighbors. Using a Set
also frees us from having to construct an Iterator
class and implement the next
and hasNext
methods, as we had to do for the BinarySearchTree
in Section 6.14.