Difference between `createTypedArrayList()` and `readTypedList()` in Parcel

Viewed 1092

While deserializing parcelables, I normally use the method createTypedArrayList (Creator<T> c) to read parcelable array lists.

I have recently found another method readTypedList (List<T> list, Creator<T> c) which seems does the exact same thing. Even the doc looks identical. Is there any difference between them apart from their implementation*?

* : The former creates new array list where the latter appends to an existing one

1 Answers

Both readTypedList() and createTypedArrayList() were written as the "read" operation to go with writeTypedList()'s "write" operation. Since they both have to operate off of the exact same data, the differences between them are relatively small.

One obvious difference is that readTypedList() will "fill up" any List implementation you'd like (e.g. LinkedList, etc) whereas createTypedArrayList() will only ever return an ArrayList.

Another is that readTypedList() allows you avoid allocating more than a single List instance if you need to run multiple "read" operations in a row; you can pass the same List instance to each invocation of readTypedList() and then handle its contents after. readTypedList() will correctly overwrite existing data and grow/shrink the list as needed to exactly fit all the newly-read data. On the other hand, createTypedArrayList() will always return a new ArrayList instance.

Probably the biggest difference, though, is how they behave when you read a null list. If the paired "write" operation had been dest.writeTypedList(null), then createTypedArrayList() can return a null value... but readTypedList() can only clear out the existing passed-in list, leaving you with an empty, non-null list. This makes it essentially impossible to tell whether the previously-written list was null or just empty, and because of this I always use createTypedArrayList().

Beyond that, there aren't any differences. Both use Creator.createFromParcel() to actually retrieve the underlying data, and both can handle null elements within the list. Again, both methods are meant to be paired with writeTypedList(), so the potential for variation between them is quite limited.

Related