Search code examples
javasortingarraylistcomparable

How to sort and retain the results of a webservice?


I have a class which has a list of objects in it. I need to sort the list based on the float value of list's objects but the following code does not work, after using Array.sort method I print out the collection but the students list would not be sorted based on GPAs.

School class

public class School{

  private List<Student> students;
  public School(){
     this.students = new ArrayList();
  }
}

Student class

public class Student implements Comparable<Student> {

 private int id;
 private float GPA;
 ...
 public int compareTo(Student student) {
        float compareGPA = student.getGPA();
        return (int)(this.getGPA() - compareGPA);
 }

}

Code to sort which is in main method

  Arrays.sort(this.school.getStudents().toArray());

Solution

  • You could sort like this:

     Collections.sort(this.school.getStudents());
    

    and you should specify <Student> here as well:

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