0

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 :) .

1
  • can you post your sort method? Commented Feb 6, 2014 at 13:38

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

Ahh such a simple fix, thank you. Is there a reason why my type does not inherit those from the Array class if it is an array itself?
Well, you have to distinguish Arrays as an Object from array as a simple built type. Here your a[] isn't an Object so it doesn't inherit from Arrays.
Actually, a[] is an Object, but it does not inherit from java.util.Arrays (note the s), as Arrays is a utility class which has nothing to with actual instances of arrays. And even if it did, Arrays does not have a sort() method with no parameters. ;)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.