1

Is the order of items in the .keySet() of a Bundle in the same order as items were inserted? I am trying to send a LinkedHashMap through a parcelable from a service to the activity.

Here is the code to insert a linkedHashMap's items into a Bundle using .putSerializable:

Bundle b = new Bundle();
Iterator<Entry<Integer, String>> _cyclesIterator = cycles.entrySet().iterator();

while (_cyclesIterator.hasNext()) {
    Entry<Integer, String> _entry = _cyclesIterator.next();

    Log.i(TAG,"Writing to JSON CycleID" + _entry.getKey());

    b.putSerializable(_entry.getKey().toString(), _entry.getValue());
}

_dest.writeBundle(b);

I am trying to read this back when the bundle is retrieved using this:

Bundle _b = in.readBundle();
if (_b != null) {
    for (String _key : _b.keySet()) {
        Log.i(TAG,"Reading JSON for cycle " + _key);
        _lhm.put(Integer.valueOf(_key), (String)_b.getString(_key));
    }
    setCycles(_lhm);
}

When items go in, the log says [1,2,3,4] but when they're read back, it is [3,2,1,4]. Is there a way to ensure the same order in both?

electrichead
  • 1,124
  • 8
  • 20

2 Answers2

1

Maps have different approach according to their use.

  • HashMap - The elements will be in an unpredictable, "chaotic", order.
  • LinkedHashMap - The elements will be ordered by entry order or last reference order, depending on the type of LinkedHashMap.
  • TreeMap - The elements are ordered by key.

For getting better idea you can also check this Answer.

Community
  • 1
  • 1
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
0

Maps and sets (and Bundles) carry no inherent order. You could serialize a single TreeMap<Integer, String> instead of iterating and serializing each entry, or you could iterate like you're doing but then also store one more value -- an ArrayList (also serializable) of the keys.

dokkaebi
  • 9,004
  • 3
  • 42
  • 60
  • Thank you. I was trying to avoid the overhead of yet another item in the Bundle, but it's essential to keep the items in order. – electrichead Jan 24 '12 at 13:45