Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert/cast HashMap to LinkedHashMap?

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?

like image 313
Emil Adz Avatar asked Aug 15 '16 14:08

Emil Adz


2 Answers

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 in 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.

like image 133
David Wasser Avatar answered Oct 01 '22 15:10

David Wasser


Just create a new LinkedHashMap, since it can take any Map as a constructor argument.

LinkedHashMap<Object> newMap = new LinkedHashMap<>(theHashMapReturnedFromHawk);

Object would be the type you need.

like image 36
Nick Avatar answered Oct 01 '22 14:10

Nick