3

I have the object below.

public class Coords {

    public int x;
    public int z;

    public Coords(int x, int z) {
        this.x = x;
        this.z = z;
    }

}

How can this implement Compareable? Im not sure what the compareTo method should be doing.

@Override
public int compareTo(Object o) {
    // TODO Auto-generated method stub
    return 0;
}
117
  • 167
  • 1
  • 2
  • 7
  • What are you trying to compare between two `Coords` objects? – Vince Jul 11 '15 at 00:38
  • 2
    im using a ConcurrentSkipList set with Coords as the object and the exception Coords cannot be cast to java.lang.Comparable is thrown – 117 Jul 11 '15 at 00:40
  • possible duplicate of [How to compare objects by multiple fields](http://stackoverflow.com/questions/369512/how-to-compare-objects-by-multiple-fields) – Steve Kuo Jul 11 '15 at 02:01

2 Answers2

2

You could compare x and then compare z (alternatively, z and then x). Also, I suggest you override toString. Something like,

public class Coords implements Comparable<Coords> {
    public int x;
    public int z;

    public Coords(int x, int z) {
        this.x = x;
        this.z = z;
    }

    @Override
    public int compareTo(Coords o) {
        if (this.x == o.x) {
            if (this.z == o.z) {
                return 0;
            }
            return this.z < o.z ? -1 : 1;               
        }
        return this.x < o.x ? -1 : 1;
    }

    @Override
    public String toString() {
        return String.format("{%d, %d}", x, z);
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Here are the details of compareTo:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

I'd suggest something like this:

@Override
public int compareTo(Coords other) {
    return this.x == other.x ? (this.z == other.z ? 0 : this.z - other.z) : this.x - other.x

You can make z more significant if you switch them.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88