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();
All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.
If you are not sure about the type of objects in the array or you want to create an ArrayList of arrays that can hold multiple types, then you can create an ArrayList of an object array.
Core Java bootcamp program with Hands on practiceA list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list); Or we can use set.
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With