I've added objects to an ArrayList
ArrayList<Pojazd> parking=new ArrayList<>();
and written the whole list as an object to a file.
void exportArrayListy() throws IOException{
FileOutputStream fo=new FileOutputStream("arraylista.ser");
ObjectOutputStream oo=new ObjectOutputStream(fo);
oo.writeObject(parking);
fo.close();
parking=null;
}
The problem is when trying to read them back as a whole:
void importArrayListy() throws IOException, ClassNotFoundException{
FileInputStream fi=new FileInputStream("arraylista.ser");
ObjectInputStream oi=new ObjectInputStream(fi);
parking=(ArrayList<Pojazd>)oi.readObject();
oi.close();
}
(Everything is in a try catch so nothing to worry about that). I get the following warning:
warning: [unchecked] unchecked cast parking=(ArrayList)oi.readObject(); required: ArrayList found: Object
Yeah, java does that unfortunately. That's one of many weird "features" in its type system. .readObject was first created before the notion of generics existed, so it is not paramterized, and is declared to return Object. If the warning bothers you, you can suppress it by adding an annotation @SuppressWarnings("unchecked")
before the function declaration.
BTW, re: "everything is in try/catch", you may want to add a finally
clause and move closing of oi
there, to avoid leaving it open in case of an exception in .readObject
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.