0

public class Student { private int studentId; // the student's identification number private String name; // the student's name private double gpa; // the student's grade point average

/***************************************************************************
 * Student
 *   The constructor for the student class
 ***************************************************************************/
public Student(int id, String theName, double theGPA)
{
    studentId = id;
    name = theName;
    gpa = theGPA;
}  // constructor

/***************************************************************************
 * toString
 *   Convert the data in a student object into a String.
 ***************************************************************************/
public String toString()
{
    return String.format("%7d %-20s %4.2f", studentId, name, gpa);
}

/***************************************************************************
 * compareTo
 *   Compare the student id of this object to that of the given object.
 * parameters:
 *   student - the given student object
 * returns:
 *   -1 if this student id is the smaller of the two id's
 *   0 if the student id's are equal
 *   1 if this student id is the larger of the two id's
 ***************************************************************************/
public int compareTo(Student student)
{
    if(student.studentId<studentId)
    {
        return -1;
    }
    else if(student.studentId>studentId)
    {
        return 1;
    }
    else
        {
            return 0;
        }
}  // compareTo

} // class Student

in the main class this is the method im trying to use:

public static void orderedInsert(ArrayList<Student>students, Student student)
{
    int size = students.size();
    int current = size -1;

    for(int i=1; i<students.size(); i++) {
        while (current >= 0 && students.get(current).compareTo(students.get(i)) > 0) {
            current--;
            students.add(current + 1, student);

        }
    }
}  // orderedInsert
Ali Khan
  • 1
  • 3

1 Answers1

0

Instead of ordering the list the way you have, you should use Collections.sort() with a comparator

Sorting Java objects using multiple keys

Mohit Mutha
  • 2,921
  • 14
  • 25