aspose file tools*
The moose likes Java in General and the fly likes Java object sorting... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java object sorting..." Watch "Java object sorting..." New topic
Author

Java object sorting...

auvrm papu
Ranch Hand

Joined: Sep 01, 2005
Posts: 105
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

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java object sorting...