androidlistarraylistparcelableonsaveinstancestate

Casting to ArrayList<? extends Parcelable> when saving List in onSaveInstanceState


I coulnd't find an answer on that:

I want to save a Parcelable ArrayList in onSaveInstanceState, but it does not accept an ArrayList that is declared as a List when I do it like this:

outState.putParcelableArrayList(KEY_QUESTION_LIST, questionList);

So I have 2 options: Either declaring the List as an ArrayList or casting it into a Parcelable ArrayList like this:

outState.putParcelableArrayList(KEY_QUESTION_LIST, (ArrayList<? extends Parcelable>) questionList);

and keeping it declared as a List:

private List<Question> questionList;

Online I only see the first approach so I wonder if there are any downsides to the 2nd approach?


Solution

  • Assuming your list is declared like this:

    List<MyObject> list = new ArrayList<>();
    

    There is no problem if you want to later write (ArrayList) list. However, I think this is a worse choice overall than simply declaring your list as an ArrayList to begin with:

    ArrayList<MyObject> list = new ArrayList<>();
    

    As Java programmers, we're taught to use the interface type for our variables because it lets us use any implementation type, not just a specific one. But in the case of putting a list into a Bundle, you need a specific implementation type. So just go ahead and use that.