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


}
3
  • 2
    Next time try Google first! "java sort array" might have worked Commented May 16, 2012 at 11:38
  • tons of duplicates : stackoverflow.com/questions/1694751/java-array-sort-descending, stackoverflow.com/questions/215271/… etc etc Commented May 16, 2012 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 Commented May 16, 2012 at 14:21

4 Answers 4

6

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

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

Comments

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.

Comments

0

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

Comments

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());

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.