Reputation: 9543
I have an array, not an arrayList and I would like to sort it. This only tells me that Collections are not applicable for the arguments (pixelPlaceSort.Pixel[], ...etc.
Collections.sort(pixels, new PixelComparator());
I could use a List to solve it but for the purpose of learning I don't want that.
So how can this work? c is an int.
class PixelComparator implements Comparator<Pixel> {
PixelComparator() {
}
public int compare(Pixel p1, Pixel p2) {
if(p1.c < p2.c) {
return -1;
} else if(p1.c > p2.c) {
return 1;
}
else {
return 0;
}
}
}
Upvotes: 0
Views: 289
Reputation: 3325
you got 2 options to sort this.
1- Keeping your Array:
your use the sort method of the "Arrays" Class:
Arrays.sort(pixels,new PixelComparator());
2- Using instead a List
you first convert your array to an List and then sort it:
ArrayList<Pixel> pixellist = new ArrayList<Pixel>(Arrays.asList(pixels));
Collections.sort(pixellist, new PixelComparator());
Upvotes: 0
Reputation: 12184
For that you have a class called Arrays.
Use Arrays.sort(pixels) Or Arrays.sort(pixels,new PixelComparator())
Check the javadoc for java.util.Arrays and chose the appropriate form of the sort() method.
Upvotes: 1
Reputation: 4185
you can use Arrays.sort(Object[] array)
or Arrays.sort(Object[] array,Comparator c)
Upvotes: 6