Keir Simmons
Keir Simmons

Reputation: 1684

Java - Unable to sort a user defined array after overriding Comparable's compareTo method

So, I am simply trying to test out how to use the compareTo method on my own types, and cannot get it to work for even the simplest of cases. My code (self explanatory) is below (it creates an array of 'numbers' from 15 -> 1 under the user defined type TestType. I would like it to be sorted 'naturally'.

public class TestType implements Comparable<TestType> {

public int n;

TestType(int _n) {
    n = _n;
}

@Override
public int compareTo(TestType otherType) {
    return this.n < otherType.n ? -1 : (this.n > otherType.n ? 1 : 0);
}

public static void main(String[] args){
    TestType[] a = new TestType[15];
    for(int i = 0; i < 15; i++){
        a[i] = new TestType(15 - i);
        System.out.println(a[i].n);
    }
    a.sort();
}
}

If you can see why it doesn't work, please let me know :) .

Upvotes: 0

Views: 121

Answers (2)

Jorge_B
Jorge_B

Reputation: 9872

Have you tried Arrays.sort(a) instead of a.sort()?

Upvotes: 0

wawek
wawek

Reputation: 1597

I think you should write Arrays.sort(a);.

Upvotes: 6

Related Questions