View Full Version : How-To Sort an Array of Objects???

02-14-2005, 06:33 AM
Hi all,

I have a little problem. I have created a Student class, which has three pieces of data in it, first name, last name, and date registered, and has a constructor, get, and set methods for each data. In my runStudent class, I allow the user to input the first name, last name, and date registered of up to 15 students. I bascially create an array (length 15) of my student objects, and store those three pieces of information in each array index.
where firstName, lastName, and registered are all strings, that have been inputed by the user in loop repetition, and i is the array index, increasing up to 15.

Now comes my problem. I am still very new to Java, and I was wondering how I can sort these object arrays, by either first name, last name, or date registered, based on the users preference. I tried using Arrays.sort(student);, but that didn't work. Just gave me errors in compiling. I tried searching the internet, and found this page: http://www.jfind.com/articles/glass040700.shtml but that didn't really help me, since that seems to only work in comparing int, double arrays, not string arrays. I would appreciate any help you all could give me. Thanks again.


02-14-2005, 05:07 PM
Are you making it so your objects can be compared to eachother? The parameter of Arrays.sort is the object array and in order to use it your objects have to implement the Comparable interface (and hence define compareTo()) in order to tell sort() how how your Objects are ordered.

See this for more info:
Arrays.sort(Object[] o): http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#sort(java.lang.Object[])
Interface Comparable: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html
Sun Java Tutorial -- Object Ordering (http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html)
Sun Java Tutorial -- Algorithms (http://java.sun.com/docs/books/tutorial/collections/algorithms/index.html)

We recently had a sorting discussion on CF, which can be found here: