Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsafe or unchecked operations warning

In an app I am using SharedPrefernces to save/load (serialize/deserialize) some objects.

This is the deserialization code:

private void loadData() {

    String str = sharedPreferences.getString(PREF_TAG, null);

    byte[] bytes = Base64.decode(str, Base64.DEFAULT);

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream input = new ObjectInputStream(bais);
        arrayOfObjects = (ArrayList<MyObject>) input.readObject();
    } catch (Exception e) {
        Log.i("BUG", "error decoding serialized objects: " + e.toString());
    }

    if (arrayOfObjects == null) {
        Log.i("BUG", "serious problem!");
    }

}

But whenever I compile this project, the line:

arrayOfObjects = (ArrayList<MyObject>) input.readObject();

causes a warning that the class containing this method "uses unchecked or unsafe operations."

How can I get rid of this warning or change my code to be more safe?

like image 334
Nerdy Bunz Avatar asked Oct 20 '25 04:10

Nerdy Bunz


1 Answers

In this case that warinig is shown because you are parsing directly the result of

input.readObject();

That returns an Object of type Object, (that is so generic), into an ArrayList, and the compiler tries to say you that, it could be any other type of objects.

In my opinion its not an important warning if that instruction in your code is always returning ArrayList, so i would add to your method definition.

@SuppressWarnings("unchecked")
like image 149
Oldskultxo Avatar answered Oct 22 '25 20:10

Oldskultxo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!