I'm getting a "Type safety: Unchecked cast from Object to ArrayList" warning on the line with readObject(), in this code snippet:
// Read the Event List
theEventArrayList = new ArrayList<Event>();
String FILENAME = "EventData.dat";
FileInputStream fis;
try {
fis = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
theEventArrayList = (ArrayList<Event>) ois.readObject();
fis.close();
}
Event
is a simple class comprised of some Strings, Calendars, booleans, and ints. The ArrayList
is written using an ObjectOutputStream in a mirror image operation to the above. The application this code is used in is executed many times a day for over a month with no failures, but the compiler warning bothers me and I don't want to just suppress it if it can be "checked" properly.
Suppress it. Your only other alternative is to cast to ArrayList, but then everywhere else in your code you have to deal with untyped ArrayList and casting on read. There is no harm in suppressing in this situation.
Well the compiler IS correct - who says that the object you're reading in really is an ArrayList? I could easily replace the file with something completely different and you'd get an exception.
Object obj = ois.readObject();
if (obj instanceof ArrayList)
// do something
else
// Error
should work. And yes you'll still get a warning because of the generic, but then that's Java's generic system, getting rid of that would mean creating a new object and adding one Event at a time - well but then we'd have to cast Objects to Events and.. argh, no not better, just live with the generic warning.
Old, but my same ol' "Got here by Google" response.
If you want to avoid it and aren't really taxed with CPU or RAM limitations, you can try Collections.copy
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