Reputation: 1684
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