5

Alright, so I have done the following:

  1. I've added objects to an ArrayList and written the whole list as an object to a file.

  2. The problem is when trying to read them back as a whole. I get the following error:

Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList at persoana.Persoana.main(Student.java:64)

Here's my code: (Everything is in a try catch so nothing to worry about that)

Writing

Student st1 = new Student("gigi","prenume","baiat","cti");
        Student st2= new Student("borcan","numegfhfh","baiat cu ceva","22c21");

        List <Student> studenti = new ArrayList<Student>();
        studenti = Arrays.asList(st1,st2);

FileOutputStream  fos = new FileOutputStream("t.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            oos.writeObject(studenti);
            oos.close();

Reading

FileInputStream fis = new FileInputStream("t.ser");
             ObjectInputStream ois = new ObjectInputStream(fis);

             ArrayList <Student> ds;

             ds = (ArrayList <Student>)ois.readObject(); 

             ois.close();

The problem occurs at this line:

ds = (ArrayList <Student>)ois.readObject();
3
  • 1
    Try (Student)ois.readObject(); Commented Jan 5, 2013 at 15:19
  • A note, here: List <Student> studenti = new ArrayList<Student>(); studenti = Arrays.asList(st1,st2); you are wasting an ArrayList Commented Jan 5, 2013 at 15:20
  • Arrays.asList() doesn't return an ArrayList. Check its javadoc. Commented Jan 5, 2013 at 15:21

2 Answers 2

9

I guess that the problem is that you are creating the List of Student through Arrays.asList. This method doesn't return an ArrayList but an Arrays.ArrayList which is a different class, meant to backen an Array and to be able to use it as a List. Both ArrayList and Arrays.ArrayList implement List interface but they are not the same class.

You should cast it to appropriate object:

List<Student> ds = (List<Student>)ois.readObject();
Sign up to request clarification or add additional context in comments.

Comments

4

Change the following lines:

ArrayList <Student> ds;
ds = (ArrayList<Student>)ois.readObject(); 

to

List<Student> ds = (List<Student>)ois.readObject();

1 Comment

No problem. See Jack's answer for an explanation of why your original code didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.