Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help Sorting Alphabetically in Java

Status
Not open for further replies.

MaxGeek

Technical User
Jan 8, 2004
52
US
I would like to sort some class objects alphabetically and want to know if there is an easy way to do it.

I have classes like Person.class which has variables like:
int id
String name
(Getters and setters for both)

Then I have a hashSet of Person.class objects and I want to return them sorted alphabetically.

Is there a relatively simple way to do this?

Thanks.
 
You didn't find the answer in the article I gave you?

Cheers,
Dian
 
I think I have an idea of how I'm going to do it. I just wanted to post it in the correct forum this time and maybe get some more advice.

I plan on getting the names out of the objects and using the compareTo() function.

This sort of got put on the back burner for me though.
 
...getting the names out of the objects and using the compareTo() function.

If your ordering is the natural ordering for your class of objects, don't get the names out of the objects just to compare them. Have the objects implement the java.lang.Comparable interface like Stefan advised. This will involve adding a compareTo method to the object class which can then do the comparison. If you've then got a collection of these objects, then use the java.util.Collections.sort(Collection c) method to sort them.

Other orderings can be created as implementations of the java.util.Comparator interface, and applied to the collection via java.util.Collections.sort(Collection c, Comparator comp).

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top