comparable

versions0135+
contributorssojamo JohnG
started on2008-08-05 20:44

taken from this discourse post, an example how to use the comparable interface to sort an array of objects based on a specific value, explained by JohnG.

// using the Comparable Interface
// http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html
// taken from post "object oriented question"
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1217951992;start=3#3
// comparable example by JohnG
 
void setup() {
  //create an array of MyObjs
  MyObj[] o = new MyObj[10];
  for(int i=0;i<o.length;i++) {
    o[i] = new MyObj(i);
  }
  // sort the array. since MyObj implements
  // the comparable interface, the MyObj list
  // will be sorted based on the outcome of
  // function toCompare
  Arrays.sort(o);
 
  // print the sorted list based on value x of
  // each object
  for(int i=0;i<o.length;i++) {
    println("id : "+o[i].id+" "+o[i].x);
  }
 
}
 
class MyObj implements Comparable {
  int x,y;
  int id;
  MyObj(int theId) {
    id = theId;
    x = int(random(100));
  }
  //if we want to sort based on the X value of MyObj-es:
  int compareTo(Object o)
  {
    MyObj other=(MyObj)o;
    if(other.x>x)  
      return -1;
    if(other.x==x)
      return 0;
    else
      return 1;
  }
}

http://processing.org comparable post

hacks/comparable.txt · Last modified: 2008-08-05 20:50 by sojamo