0

Looking at the docs for Parcel#writeMap(Map), it clearly states that "The Map keys must be String objects", however looking at the code there seems to be absolutely no reason for this aside from completely unnecessary casting:

/* package */ void readMapInternal(Map outVal, int N,
    ClassLoader loader) {
    while (N > 0) {
        Object key = readValue(loader);
        Object value = readValue(loader);
        outVal.put(key, value);
        N--;
    }
}

/* package */ void writeMapInternal(Map<String,Object> val) {
    if (val == null) {
        writeInt(-1);
        return;
    }
    Set<Map.Entry<String,Object>> entries = val.entrySet();
    writeInt(entries.size());
    for (Map.Entry<String,Object> e : entries) {
        writeValue(e.getKey());
        writeValue(e.getValue());
    }
}

Is there anything I am missing here? It's important for me to know since I am writing a library that heavily uses this class and it seems like a massive restriction for no reason.

EDIT: Similarly, when writing SparseArray objects, this class forces you to pass in only SparseArray<Object>:

public final void writeSparseArray(SparseArray<Object> val)

This is another restriction that makes no sense. Are these Android API bugs?

EDIT: This answer seems to also imply there is a bug

Community
  • 1
  • 1
Bradley Campbell
  • 7,300
  • 5
  • 32
  • 45
  • so why dont you use `writeBundle` instead? – pskink Jan 12 '16 at 08:39
  • Bundles also require String keys. To me, the writeMap function seems like it would work fine without the String key. – Bradley Campbell Jan 12 '16 at 08:45
  • and what type of keys do you want to have (if not String)? – pskink Jan 12 '16 at 08:50
  • I'm wanting to handle all types of parcelable maps. For argument sake, let's say the key is just some random object that implements Parcelable – Bradley Campbell Jan 12 '16 at 08:54
  • so write `writeYourMap` helper method that writes the size first and then, in a loop, writes a key followed by a value, and of course you should write `readYourMap` as well – pskink Jan 12 '16 at 09:06
  • Yes but that's exactly what the provided methods are doing, except with a seemingly unnecessary requirement to have a String key. Hence the question – Bradley Campbell Jan 12 '16 at 09:09
  • it seems they did it to be coherent with the other "container" like objects like Bundle and Intent where all the keys are Strings – pskink Jan 12 '16 at 09:18
  • As far as I know you are not able to cast the key when you try to get the entry set, so a generic `Object` wouldn't work in this case. What you are looking for is this probably: [ParcelableMap storing](http://stackoverflow.com/a/25557925/602549) – racs Jan 12 '16 at 19:51
  • But as long as the object fits into the specification provided by writeValue(value), which is what this method uses internally, I think it should be fine. – Bradley Campbell Jan 14 '16 at 05:02

0 Answers0