David Lawlor
David Lawlor

Reputation: 53

Cannot be cast to java.util.ArrayList

Trying to write an object to an array and then save to output.data, then read the objects again.

Writing:

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        

    File outFile;
    FileOutputStream fStream;
    ObjectOutputStream oStream;

    try {
        outFile = new File("output.data");
        fStream = new FileOutputStream(outFile);
        oStream = new ObjectOutputStream(fStream);

        oStream.writeObject(arr);

        JOptionPane.showMessageDialog(null, "File Written Successfully");

        oStream.close();
    } catch (IOException e) {
        System.out.println("Error: " + e);
    }
}                  

Reading:

private void readBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        

    File inFile;
    FileInputStream fStream;
    ObjectInputStream oStream;

    try {
        inFile = new File("output.data");
        fStream = new FileInputStream(inFile);
        oStream = new ObjectInputStream(fStream);

        //create an array of assessments
        ArrayList <Assessment> xList;
        xList = (ArrayList<Assessment>)oStream.readObject();



        for (Assessment x:xList) {
            JOptionPane.showMessageDialog(null, "Name: " + x.getName() + "Type: " + x.getType() + "Weighting: " + x.getWeighting());
        }

        oStream.close();
    } catch (IOException e) {
        System.out.println("Error: " + e);
    } catch (ClassNotFoundException ex) {
        System.out.println("Error: " + ex);
    }


}                      

The code comppiles just fine, and the file itself saves alright too. But when I try to read the file nothing happens, and NetBeans says

"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Lnetbeansswingexample.Assessment; cannot be cast to java.util.ArrayList"

the line of code giving trouble seems to be

xList = (ArrayList<Assessment>)oStream.readObject();

Any help would be really appreciated, thanks. Sorry if the answers obvious, pretty new to programming.

Upvotes: 3

Views: 31448

Answers (1)

Eran
Eran

Reputation: 393781

Based on the exception you got, it looks like oStream.readObject() returns an array of Assessment, not a List. You can convert it to a List:

    List <Assessment> xList;
    xList = Arrays.asList((Assessment[])oStream.readObject());

or if you must use a java.util.ArrayList :

    ArrayList<Assessment> xList;
    xList = new ArrayList<> (Arrays.asList((Assessment[])oStream.readObject()));

Upvotes: 5

Related Questions