Hey guys, check this out:

File test = new File(path + "person.data");
FileOutputStream fos = new FileOutputStream(test);
ObjectOutputStream oos = new ObjectOutputStream(fos);
		
Person p = new Person();
Person p2 = new Person();
		
p.setName("Sub Zero");
p.setGender("Male");
p2.setName("Sonya Blade");
p2.setGender("Female");
		
ArrayList<Person> people = new ArrayList<Person>();
ArrayList<Person> people2 = new ArrayList<Person>();
		
people.add(p);
people.add(p2);
		
oos.writeObject(people);
System.out.println("People array has been written");
oos.close();
		
FileInputStream fis = new FileInputStream(test);
ObjectInputStream ois = new ObjectInputStream(fis);
people2 = (ArrayList<Person>) ois.readObject();
		
Person m = people2.get(1);
System.out.println("From file: " + m.getName() + ", " + m.getGender());
fis.close();

This works. However, my IDE puts a yellow line underneath the code "people2 = (ArrayList<Person>) ois.readObject()", giving me the warning: unchecked cast from object to arraylist<Person>.

Should I ignore the warning, or is there a better way to code this?

readObject returns an Object, and given that it's reading it from a Stream at runtime, there's nothing else it can do. You have to cast it to the right class before you can use it fully. There's no way to avoid an unchecked cast in this case. You may want to use instanceof to check what kind of Object has actually been read before casting, but all that does is allows you to handle any errors gracefully.

hi james,

thanks. Ive been trying to modify that code to include instanceOf but I'm having trouble. This is the code I wrote:

Object o = ois.readObject();
if(o instanceof Person) {
people2 = (ArrayList<Person>) ois.readObject();
} else {
System.out.println("Not a person");
}

It keeps coming up with "not a person". Can you pls help correct it?

Oh, sorry lol. But it wouldn't let me use ArrayList<Person>. I had to opt for generics ArrayList<?>, which worked fine.

Thanks

This question has already been answered. Start a new discussion instead.