Reputation: 53
Alright, so I have done the following:
I've added objects to an ArrayList and written the whole list as an object to a file.
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();
Upvotes: 5
Views: 18297
Reputation: 133567
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();
Upvotes: 9
Reputation: 15479
Change the following lines:
ArrayList <Student> ds;
ds = (ArrayList<Student>)ois.readObject();
to
List<Student> ds = (List<Student>)ois.readObject();
Upvotes: 4