Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unchecked cast warning - how to avoid this? [duplicate]

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.

like image 517
Peter Nelson Avatar asked Mar 05 '11 03:03

Peter Nelson


3 Answers

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.

like image 175
Konstantin Komissarchik Avatar answered Oct 16 '22 19:10

Konstantin Komissarchik


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.

like image 25
Voo Avatar answered Oct 16 '22 20:10

Voo


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

like image 22
Joe Plante Avatar answered Oct 16 '22 21:10

Joe Plante