Search code examples
arraysclasscastexceptionserializable

Why do I get ClassCastException when trying to read objects from my file?


I get a runtime-error that says: Exception in thread "main" java.lang.ClassCastException: lab07.Loan cannot be cast to [Llab07.Loan; at lab07.TestLoanClass.main(TestLoanClass.java:27).

The fault might be in the serializable class Loan, but have a look at this one first. Because it all works just fine if I avoid using arrays. I am using the Eclipse IDE.

public class TestLoanClass {

public static void main(String[] args) throws IOException,
        ClassNotFoundException {
    Loan[] loan = new Loan[5];

    ObjectOutputStream output = new ObjectOutputStream(
            new FileOutputStream("Exercise19_06.dat"));

    for (int i = 0; i < 5; i++) {
        loan[i] = new Loan(1.5 * i,i * 2,10000 * i);
        output.writeObject(loan[i]);
    }
    output.close();

    ObjectInputStream input = new ObjectInputStream(new FileInputStream(
            "Exercise19_06.dat"));


    //Conversion below is perfectly legal to type, but I get an error when 
    //I run the program. Appearently it has something with Object being 
    //cast to a Loan. Shouldn't the error show up while writing the code?

      Loan[] loanRead = (Loan[]) (input.readObject());

    //However, it work's just fine if I avoid using an array

    for (int j = 0; j < 5; j++) {

        System.out
                .printf("The loan was created on %s\n"
                        + "The monthly payment is %.2f\nThe total payment is %.2f\n",
                        loanRead[j].getLoanDate().toString(),
                        loanRead[j].getMonthlyPayment(),
                        loanRead[j].getTotalPayment());
    }

    input.close();
}

}


Solution

  • Delete Loan[] loanRead = (Loan[]) (input.readObject()); and put loan[j] = (Loan) (input.readObject()); in a second for loop.

    And of course change all occurences of loanRead[j] in a for loop with loan[j].