Reputation: 29
I know that compareTo can return positive negative and zero values.
So if I use
public class x implements Comparable <Object O> {/*...*/}
and assign inside
public int compareTo(int i) {
if (this.intg < i) { return -1; }
else if (this.intg > i) { return 1; }
else { return 0; }
}
Will I be able to use sort Array.sort(O[]objects)
in this way?
I do not know the connection of array.sort()
and compareTo()
.
It even does not call the compare method to sort it.
So what does the compareTo()
input really do? Where can I pass it if I cannot call this method when I use array.sort()
Upvotes: 1
Views: 7214
Reputation: 446
Generally you'd be better creating a Comparator rather than implementing Comparable. You can then pass that to the Collections sort method:
Collections.sort(myArrayList, new Comparator<MyObject>(){
public int compare(MyObject o1, MyObject o2){
return Integer.compare(o1.value == o2.value);
}
});
EDIT:
After reading some of the OPs comments, we can demonstrate that the compareTo method is indeed being called:
public class TestClass implements Comparable<TestClass> {
private int value;
public int getValue(){
return this.value;
}
public void setValue(int v){
this.value = v;
}
@Override
public int compareTo(TestClass arg) {
System.out.println("In compareTo");
return Integer.compare(this.value, arg.value);
}
}
If we then do the following:
ArrayList<TestClass> a = new ArrayList<>();
for( int i = 0; i < 10; i++ ){
TestClass t = new TestClass();
t.setValue(i);
a.add(t);
}
System.out.println("Before sort.");
Collections.sort(a);
We'll see that the compareTo method is being called from within the sort method, as the terminal will show our trace statements:
Before sort.
In compareTo
In compareTo
In compareTo
In compareTo
In compareTo
In compareTo
In compareTo
In compareTo
In compareTo
Upvotes: -1
Reputation: 32758
You can use the Collections.sort
method to do sort-in-place a List
of your objects. The 2nd argument is your Comparator
implementation.
Example:
List<Animal> animals = .. some ArrayList for example;
Comparator<Animal> comparator = new Comparator<Animal>() {
public int compare(Animal d1, Animal d2) {
int v1 = d1.intg;
int v2 = d2.intg;
return (v1 > v2 ? 1 : (v1 == v2 ? 0 : -1));
}
};
Collections.sort(animals, comparator);
// the 'animals' collection is now sorted based on the `intg` property
Upvotes: -1
Reputation: 72874
Here's the Javadocs of Arrays.sort(Object[])
:
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is,
e1.compareTo(e2)
must not throw aClassCastException
for any elementse1
ande2
in the array).
So the sort method does rely on the Comparable
interface of the array elements.
Upvotes: 3