I have an ArrayList composed of Student objects. These objects contain first name, last name, lab grade, project grade, exam grade, and total grade. I am trying to write a function that sorts the Student objects in the ArrayList based on their total grade.
Here's my Student class:
public class Student {
// fields
private String firstname;
private String lastname;
private int labgrade;
private int projectgrade;
private int examgrade;
private int totalgrade;
// constructor
public Student(String firstname, String lastname, int labgrade,
int projectgrade, int examgrade) {
this.firstname = firstname;
this.lastname = lastname;
this.labgrade = labgrade;
this.examgrade = examgrade;
this.totalgrade = labgrade + projectgrade + examgrade;
}
// method
public String toString() {
String s = firstname + " " + lastname + " has a total grade of "
+ totalgrade;
return s;
}
public int compareTo(Student s) {
return (totalgrade = s.totalgrade);
}
And here's what I tried to do to sort:
private ArrayList<Student> arraylist = new ArrayList<Student>();
public void SortStudent() {
Collections.sort(arraylist);
}
But that doesn't work because it says it can only work on List not ArrayList. Any help to fix my SortStudent method?
ArrayListis aList.compareTo()is wrong.totalgrade = s.totalgradeis an assignment, not a comparison. To compare, usereturn Integer.compare(this.totalgrade, s.totalgrade).