SortedSet - sorting and equality tests not working as expected
<p>I have instances of a class which I'd like to sort in a particular order, but also be able to tell if an instance exists in a set using a <em>different</em> criteria. Example:</p>

<pre><code>public class Foo {
    int x;
    int y;

    public Foo(int x, int y) { this.x = x; this.y = y }

    // equality determined by value of 'x':
    @Override 
    public boolean equals(Object obj) {
        if (obj instanceof Foo) {
            return ((Foo)obj).x == this.x;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return this.x;
    }

    @Override
    public int compareTo(Foo foo) {
        if (this.x &lt; foo.x return -1;
        else if (this.x &gt; foo.x return 1;
        return 0;
    }
}

...

// Would like to keep a set of Foos, but sorted by 'y' value.
// Passing in an explicit comparator which sorts on 'y'.
SortedSet&lt;Foo&gt; test = new TreeSet&lt;Foo&gt;(new ComparatorFoo());

public static class ComparatorFoo implements Comparator&lt;Foo&gt; {
    @Override
    public int compare(Foo o1, Foo o2) {
        if (o1.y &lt; o2.y) return -1;
        else if (o1.y &gt; o2.y) return 1;
        return 0;
    }
}
</code></pre>

<p>Now trying:</p>

<pre><code>test.add(new Foo(3, 4));
test.add(new Foo(1, 2));
test.add(new Foo(5, 6));

// sorts by 'y' ok.
for (Foo foo : test) {
    System.out.println(foo.toString());
}

// but can't find an instance with the same 'x' value:
test.contains(new Foo(1, 999));
</code></pre>

<p>Do I need to keep two separate data structures to do this? (One for sorting, one for equality testing?)</p>

<p>Thank you</p>

<p>------ Update ---------</p>

<p>End result: the comparator used to initialize the SortedSet also gets used when contains() is invoked. Therefore I couldn't have the set sorted by 'y', and check for existence of an element by 'x'.</p>
