Java, sorting array of objects

Carlis

Senior member
May 19, 2006
237
0
76
Hi
Im trying to get my program to sort an array of objects but I get "java.lang.ClassCastException:" at Arrays.sort(stud) below. So java thinks I have casted an object of the wrong kind. But the "compareTo" method has arg Student and "stud" is clearly a collection of Student objects. What did I do?
-------------------------------------------------------------------
import java.io.IOException;
import java.util.*;
import javax.swing.*;



public class Betygslistor {
Fileread F;
Student[] stud;


public static void main(String[] args) throws IOException{
new Betygslistor();

}

public Betygslistor() throws IOException{
F=new Fileread();
arrangeStuds();

}
public void arrangeStuds(){
stud=F.getStuds(); //gets objects created in "Fileread F"
Arrays.sort(stud); ***Error here***

}

}

------------------------------------------------------------

public class Student implements Comparable<Student>{

(fields)*

public int compareTo(Student S) {

String SeName=S.geteName();

int comp=this.eName.compareTo(SeName);
return(comp);
}
.........
 

Brett

Senior member
Oct 15, 1999
377
0
76
Can you post a stack trace? Its hard to debug with what you've given. More context would also make it easier. The only thing I can see is that you might want to change your compareTo method to be like this:

public int compareTo(Object o) {
if(!(o instanceof Student)){
return -1;
}

Student s = (Student) o;

return this.eName.compareTo(s.geteName());
 

Carlis

Senior member
May 19, 2006
237
0
76
Hi again. After reading a lot of sun manuals I managed to solve the problem with a different approach. Thanx any way.