سؤال

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());
هل كانت مفيدة؟

المحلول

You could sort like this:

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

and you should specify <Student> here as well:

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

نصائح أخرى

The problem is you are sorting an intermediate result - an array that is not stored anywhere - and you are not doing anything with it.

What you are basically doing now is:

Object[] intermediate = this.school.getStudents().toArray();
Arrays.sort(intermediate);
//do nothing with intermediate

The solution will be to use Collections.sort() instead (better) - or to store the intermediate array, sort it, and then revert it back to your students list (worse)

this.school.getStudents().toArray() creates a temporary array instance and Array.sort() sorts the temporary array, not your actual ArrayList. You could use Collections.sort(this.school.getStudents()); instead

You could either use Collections.sort(this.school.getStudents()); or Collections.reverse(this.school.getStudents()); for ascending and descending order respectively.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top