Skip to main content
gamedev.net
🔒 Locked

Sorting objects based on a variable? (Java)

Started by ShauwnBlue Jan 17, 2007 at 12:42 AM 3 replies 1.4k views
Original Post
ShauwnBlue
ShauwnBlue
I'm trying to think of how I can order objects based on an instance variable in each one. Let's say I have a class called Task, and each Task object has an int variable 'priority'. How could I sort all the task objects from highest priority to lowest? I'm currently using 3 boolean variables and a handful of if statements, but I know this is a horrible way of doing this. An array would make it much easier, but I am not sure of how to go about sorting an array of Task objects based on their 'priority' variable. Can anyone point me in a direction of where to start on this? Thanks for any help.
sphen_lee
sphen_lee
Sorting objects really only makes sense if they are in some kind of array (in Java either a primitive array, an ArrayList or similar).

Search for "bubble sort", its the simplest sort, and fast if the objects are mostly in order.
ShauwnBlue
ShauwnBlue
Bubble sorting seemed to do the trick.
Thanks for the help guys.
Fred304
Fred304
Quote:
Original post by ShauwnBlue
I'm trying to think of how I can order objects based on an instance variable in each one.

Have the class implement the Comparable interface. In the compareTo method, compare the instance variable. Then you should be able to sort a collection containing Tasks.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.