Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java object sorting...

 
auvrm papu
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question in Sorting....

I hava object, lets say car

and it has the properties:
car_id
color,
year,
make
cost,

Lets say I have 10 cars...

and I want to sort the cars in this following order...
order by color, then order by year..., make, cost...

So basically,
for ex:

I have 5 red cars, 3 blue and 2 green...
ex: 1-Red,2-Red, 3-Red, 4-Red, 5-Red

sort those 5 red cars then by year....say... 1-Red=1996, 3-Red=1996, 4-Red=1996, 5-Red=1998, 2-Red=1999.....etc

then sort by make....
say..

4-Red=1996=Dodge, 3-Red=1996 =Dodge, 1-Red=1996=Toyoto, etc

then by cost

3-Red=1996=Dodge=16K, 4-Red=1996 =Dodge=17K, etc

You get the point....?


what is the best way to do this........

Thanks!
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A common way to do this in Java is to write a Comparator. You compare starting with the most significant field (color) and then progressively less significant.


Then if you have a List of Car objects you can just say:

java.util.Collections.sort(carList, new CarComparator());

Or if you have an array:

java.util.Arrays.sort(carArray, new CarComparator());
[ March 01, 2007: Message edited by: Garrett Rowe ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic