How to convert/cast HashMap to LinkedHashMap?

Emil Adz picture Emil Adz · Aug 15, 2016 · Viewed 14.8k times · Source

I'm using Hawk as a replacement for SharedPreferences in my application.

I'm trying to store a LinkedHashMap in it, but for some reason when I pull it back from Hawk it returns as a regular HashMap and not a LinkedHashMap. At this point I crash with a ClassCastException as HashMap can't be casted to LinkedHashMap straight forward.

So the question is how can I convert the returned HashMap to be a LinkedHashMap?

Answer

David Wasser picture David Wasser · Aug 15, 2016

All the answers suggesting that you can create a LinkedHashMap from a HashMap are technically correct, but will not give you the desired results :-(

Of course, you can create a LinkedHashMap from a HashMap, but it isn't guaranteed that the LinkedHashMap will have the same order that your original did.

The problem is that your LinkedHashMap is serialized when it is stored into the persistent storage as a plain unordered Map, which does NOT persist the ordering of the individual items. When you then extract the object from the persistent storage, it is returned as a plain HashMap, and it has lost the "ordering" (which is what you wanted a LinkedHashMap for in the first place). If you then create a LinkedHashMap from the returned HashMap, the ordering will most probably be different from the original.

In order to do this correctly, you should probably convert your LinkedHashMap into an ordered array of objects and store this ordered array in the persistent storage. You can then read the ordered array of objects back from the persistent storage and recreate the LinkedHashMap with the correct order. Basically, you need to serialize and deserialize the LinkedHashMap yourself.

See my answer to this question for more details.