Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2005
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How-To Sort an Array of Objects???

    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.
    i.e.:
    student[i].setFirstName(firstName);
    student[i].setLastName(lastName);
    student[i].setRegistered(registered);
    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.

    SuperG
    Last edited by SuperG; 02-14-2005 at 06:36 AM.

  • #2
    cfc
    cfc is offline
    Regular Coder
    Join Date
    Dec 2004
    Location
    Keswick, Ontario
    Posts
    251
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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/....Object[])
    Interface Comparable: http://java.sun.com/j2se/1.5.0/docs/...omparable.html
    Sun Java Tutorial -- Object Ordering
    Sun Java Tutorial -- Algorithms

    We recently had a sorting discussion on CF, which can be found here:
    don't know about Sorting Algorithms?
    Last edited by cfc; 02-14-2005 at 05:20 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •