Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey,
I have a problem, I get an error in my java code, I'm not sure to understand why it is there. What I am trying to do is to print the city of each student. student is an object, which as one function which is city. City will return a string if called. Each student object is stored in an arrayList called full.
Here is my code:

Java
for (int i = 0; i < full.size(); i++){
            System.out.println(full.get(i).city().toString());
        }


and the error is the following:

Exception in thread "Thread-0" java.lang.ClassCastException: java.lang.String cannot be cast to components.Student
	at components.ClientThread.createTable(ClientThread.java:202)
	at components.ClientThread.run(ClientThread.java:88)
Posted
Comments
Richard MacCutchan 21-Dec-14 3:19am    
Are you certain that is the line where the error occurs? Also, why are you calling toString on a string object?
Member 11322545 21-Dec-14 7:55am    
wall, that is was eclipse says and I called toString to try, I also tried without it and same error.
Richard MacCutchan 21-Dec-14 8:35am    
Eclipse does not say such things. You need to understand that if a method returns a string then you do not need to (and should not) call toString on it. And you have not answered my first question, I suspect the code you have shown us is not where the error occurs.
Member 11322545 21-Dec-14 8:50am    
The line number from eclipse is that line, exactly that line. I do understand that, and I have tried without the toString but no result. I have tried to remove the line, and when I remove it no problem.

1 solution

Well, seems like you're returning an Object there.

Heave you debugged it?

Try this instead:

Java
for (int i = 0; i < full.size(); i++)
{
  City city = full.get(i).city();
  Student student = city.getStudent(); // or what ever that is
  System.out.println("City: " + city.toString() + "\tStudent: " + student.toString()); // if you have set the toString(), otherwise a String representing the object is used.
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900