Sorting array objects in Processing 2.0+

edited July 2014 in How To...

I am getting this error while trying to sort an array of objects:

the method sort (byte[]) in the type PApplet is not applicable for the arguments (sketch_124453.Word[])

To support sort, I saw that one has to implement Comparable, hence my class code below.

But its not working so i wonder if sorting object arrays is possible with Processing 2.0+? Is this solution approach that I have done specific only to Processing 1.0.

class Word implements Comparable  {
  String s;
  int n=0;
  Word(String theWord) {
    s = theWord;
    n = 1;
  }
  //if we want to sort based on the n value of Word object:
  int compareTo(Object o)
  {
    Word other=(Word)o;
    if(other.n>n)  return -1;
    if(other.n==n) return 0;
    return 1;
  }

  int compareTo(Word o)
  {    
    if(o.n>n)  return -1;
    if(o.n ==n) return 0;
    return 1;
  }
}
Tagged:

Answers

  • In your class n always has the value 1 so all Word objects are the same so sorting will not occur.

    I am getting this error while trying to sort an array of objects:

    What type of objects?

  • You don't even show us how you try to sort your array!

    Processing' sort() function works only with arrays of primitives. To sort a Java array, you have to use Arrays.sort(yourArray); (sort in place).

    Note also you have to get rid of the second compareTo, useless and can confuse the compiler.

  • edited July 2014

    Processing's sort() function works only with arrays of primitives.

    You've forgotten String[]! O:-) Therefore, if @pbvillaflores needs only to sort() String objects,
    there's no need to go all the way down to implement Comparable!

    Although particularly I prefer java.util.Arrays.sort(), b/c it acts upon the passed array
    rather than instantiate another 1 as Processing's sort() does!

  • Well, String is almost a primitive! ;-)
    Obviously, the OP wants to sort his array of Word objects.

Sign In or Register to comment.