Hi everyone,

I'm not exactly new to Java, but I have a more extensive background in C++.

My problem is I'd like to define two different equality relations on the same class.

Using comparators, I can define additional orderings between elements aside from the "natural" ordering provided by the Comparable interface. I can then pass this comparator to a TreeSet to get the appropriate ordering, which in the following example eliminates duplicates either based on the unique ID (don't allow the same object twice) or the content (don't allow the same content twice).

Code:
class A implements Comparable<A> {
    final int uniqueID;

    int content;

    int compareTo(A other) {
        return this.uniqueID - other.uniqueID;
    }

    public static ContentComparator implements Comparator<A> {
        public int compare(A a1, A a2) {
            return a1.content - a2.content;
        }
    }
}

TreeSet<A> noIDDuplicates = new TreeSet();
TreeSet<A> noContentDuplicates = new TreeSet(new ContentComparator());
However, I can't seem to find a way of doing the same thing using HashSets. The HashSet implementation uses the equals() and hashCode() functions to test for equality, and I haven't seen any constructors taking a custom hashCode/equality functions as parameters.

Code:
class A implements Comparable<A> {
    ...

    boolean equals(A other) {
        return this.uniqueID == other.uniqueID; // or equivalently, return this == other;
    }
    int hashCode() {
        return this.uniqueID;
    }
}

HashSet<A> noIDDuplicates = new HashSet();
HashSet<A> noContentDuplicates = ???
In C++ additional hashing/equality pairs are supported through template parameters.

So my question then: is there another type of HashSet which accepts a custom equality relation (not the "natural" one)? Or do I have to wrap my objects in another class defining the extra relation, before adding them to the HashSet?

Thanks!
Simon