0

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; 
    }
  }


}
PeskyGnat
  • 2,454
  • 19
  • 22
clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • 2
    Next time try Google first! "java sort array" might have worked – John B May 16 '12 at 11:38
  • tons of duplicates : http://stackoverflow.com/questions/1694751/java-array-sort-descending, http://stackoverflow.com/questions/215271/sort-arrays-of-primitive-types-in-descending-order etc etc – kostja May 16 '12 at 11:39
  • i really did a search! Found mostly stuff where Integer would be used to solve the problem or convert to list and convert back. But maybe i should have searched some longer, sry for that then – clankill3r May 16 '12 at 14:21

4 Answers4

6

you can use Arrays.sort(Object[] array) or Arrays.sort(Object[] array,Comparator c)

narek.gevorgyan
  • 4,165
  • 5
  • 32
  • 52
1

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.

Amogh Talpallikar
  • 12,084
  • 13
  • 79
  • 135
0

Use the Arrays class - specifically this Arrays.sort() method.

Nate
  • 16,748
  • 5
  • 45
  • 59
0

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());
arthur
  • 3,245
  • 4
  • 25
  • 34