We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › sorting an array of objects
Page Index Toggle Pages: 1
sorting an array of objects (Read 1511 times)
sorting an array of objects
May 9th, 2008, 7:06am
 
i've got an array of objects with 3 variables: posX, posY and distance
how do i sort the array with ascending distance?

i tried using the arrays.sort() but it always gives me this error which i have no idea what it is

java.lang.ClassCastException: Temporary_198_139$OneMinute
at java.util.Arrays.mergeSort(Arrays.java:1156)
at java.util.Arrays.sort(Arrays.java:1080)
at Temporary_198_139.SortMinutes(Temporary_198_139.java:104)
at Temporary_198_139.AssignPosition(Temporary_198_139.java:95)
at Temporary_198_139.draw(Temporary_198_139.java:42)
at processing.core.PApplet.handleDisplay(PApplet.java:1465)
at processing.core.PGraphics.requestDisplay(PGraphics.java:690)
at processing.core.PApplet.run(PApplet.java:1562)
at java.lang.Thread.run(Thread.java:613)

at java.util.Arrays.mergeSort(Arrays.java:1156)
at java.util.Arrays.sort(Arrays.java:1080)
at Temporary_198_139.SortMinutes(Temporary_198_139.java:104)
at Temporary_198_139.AssignPosition(Temporary_198_139.java:95)
at Temporary_198_139.draw(Temporary_198_139.java:42)
at processing.core.PApplet.handleDisplay(PApplet.java:1465)
at processing.core.PGraphics.requestDisplay(PGraphics.java:690)
at processing.core.PApplet.run(PApplet.java:1562)
at java.lang.Thread.run(Thread.java:613)
Re: sorting an array of objects
Reply #1 - May 9th, 2008, 9:31am
 
arrays.sort() only knows how to sort objects that implement the Comparable interface. Otherwise how on earth will it know how to sort them?

See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html
Re: sorting an array of objects
Reply #2 - May 15th, 2008, 8:53am
 
check this post for the Comparator thing:
http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Syntax;action=display;num=1210524369;start=0
Re: sorting an array of objects
Reply #3 - May 15th, 2008, 9:06am
 
Warning this is a VERY dirty hack.

But you could take the fields of the array and create a String array with the field that you want to sort by at the start of the String. Sort the String array. and then you take the String array split it and move the new values back into the array of objects.

Again I'm sorry. I know it's a very crap way of doing it but it will work.

MattD
Page Index Toggle Pages: 1