A question for all the java wizards?

Ok, so I'm making a program that asks users for info about students (name, gender, etc) and I want to be create many student objects and sort them by name, gender, and everything else. Is there a way I can take the stuff the user inputs (gender, name, etc) and create an object with those attributes? If not, is there another way to sort the students?

Kaydell2013-01-10T00:32:37Z

Favorite Answer

Here's one approach:

1. Create a class named Student.
2. Create a list of student objects with the following line of code:

ArrayList<Student> students = new ArrayList<Student>();

3. Have a loop and ask for all of the attributes of one student each time through the loop
4. Create one student object each time through the loop.
5. Add the student object that is created each time through the loop to the list of students

students.add(student);

After the end of of the loop, you can sort the list of students with the following statement

Collections.sort(students);

The above line of code will sort the students by their natural ordering which is what is defined by the method called compareTo() which is a method of the Student class.

To sort different ways, implement a class that implements the Comparator interface.

Here's a link to a web page that is a tutorial for sorting Collections such as students.

http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

green meklar2013-01-10T02:59:00Z

Of course.