I need to sort a linked list of StudentInfo objectsx using compareTo().
This is my StudentInfo clas
package mahaffy_lab4;
import java.util.*;
/**
*
* @author student
*/
public class StudentInfo implements Comparable<StudentInfo>
{
private LinkedList<Object> classes = new LinkedList<>();
private String sid, name;
public StudentInfo(String sid, String name)
{
this.sid = sid;
this.name = name;
}
public void AddClass(Object aClass)
{
classes.add(aClass);
}
@Override
public int compareTo(StudentInfo studentA)
{
return this.name.compareTo(student.name);
}
@Override
public String toString()
{
return "Name: " + name + " SID: " + sid;
}
}
But this is where my issue is. in my main/test class, nothing i have tried works. this is the last try I made:
private LinkedList<Object> students = new LinkedList<>();
public String GetAllStudents()
{
Collections.sort(students, new Comparator<String>() {
@Override
public int compare(StudentInfo o1, StudentInfo o2) {
return Collator.getInstance().compare(o1, o2);
}
});
return students.toString();
}
Please, any help would be appreciated.
The problem is in the declaration:
private LinkedList<Object> students = new LinkedList<>();
LinkedList is a list of Object
, so values of the list are compared as Object
, not as StudentInfo
.
To fix the problem, re-declare the list:
private LinkedList<StudentInfo> students = new LinkedList<>();