2

I'm getting odd warnings in my reading of a ArrayList of Serializable objects. Here is the code:

public void loadBoard() {
    FileInputStream fis = null;
    ObjectInputStream is;
    try {
        fis = this.openFileInput(saveFile);
        is = new ObjectInputStream(fis);
        // Build up sample vision board
        if (mVisionBoard == null) {
            mVisionBoard = new ArrayList<VisionObject>();
        } else {
            mVisionBoard.clear();
        }
        ArrayList<VisionObject> readObject = (ArrayList<VisionObject>) is.readObject();
        mVisionBoard = readObject;
        is.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e(TAG, "loadBoard failed: "+e);
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
        Log.e(TAG, "loadBoard failed: "+e);
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(TAG, "loadBoard failed: "+e);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        Log.e(TAG, "loadBoard failed: "+e);
    }
}

and the warning I'm getting is (on readObject line):

"Type safety: unchecked cast from Object to ArrayList"

The few examples I've read indicate that this is the correct code for reading an ArrayList of serializable objects. The code I made to write the arraylist isn't giving me any warnings. Am I doing something wrong here?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Alan Moore
  • 6,525
  • 6
  • 55
  • 68

1 Answers1

1

kind of late but it will help someone...

the reason of the warning is because of the return of the method readObject...

see:

  public final Object readObject()

it returns actually an object

and if you just by mistake read and deserialize a lets say String object ant try to cast that into an array list then you will get a runtime execption (the reason must be obvious)

in order to avoid that predictable failure you can check the type of the returned object before the cast...

that is why you get the warning:

"Type safety: unchecked cast from Object to ArrayList<VisionObject>"

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97