Friday, May 21, 2010

How do I sort an arraylist of objects in Java?

I am making a address book in Java. I take the user input and store it into an object called entry. I then take the object and add it to an arraylist called entry_list. Each object has a method called getLName() that recalls the last name of the entry object. How would I sort the arraylist by last name?

How do I sort an arraylist of objects in Java?
Wow - it's been a while, but I did this exact thing in college, and if I remember correctly, I had to basically "create" my own sort method, becuase arraylists hold objects which don't lent themselves to sorting too well. Now, I can't remember if their is a native "sort" method for arraylists in Java ( I don't think there is). If there is, it would have to be overridden. If not, you would need to create a method from scratch, and pass the arraylist to it. In the method, you would need to go through each object in the list, and do sorting algorithm based on the last name property of each object. I don't have acccess to my source code now, but if you get stuck, let me know, and I will check it out when I get home. Good luck.
Reply:Take a look at this example from Java Almanac. If you work with a Collections object, you get the sort() method.
Reply:check this out:





http://mindprod.com/jgloss/sort.html

id cards

No comments:

Post a Comment