Sorting with Comparable
From Processing
| Versions: | 1.0+ |
| Contributors: | sojamo, JohnG |
| Started: | 2008-08-05 |
Taken from this discourse post, a snippet to show how to use the Comparable interface to sort an array of objects based on a specific value.
Source Code
// 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; } }