• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java, sorting array of objects

Carlis

Senior member
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);
}
.........
 
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());
 
Hi again. After reading a lot of sun manuals I managed to solve the problem with a different approach. Thanx any way.
 
Back
Top