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");
p2.setName("Sonya Blade");
ArrayList<Person> people = new ArrayList<Person>();
ArrayList<Person> people2 = new ArrayList<Person>();
System.out.println("People array has been written");
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());

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?

Recommended Answers

All 4 Replies

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?

its an instance of ArrayList<Person> ?

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


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.