I need a data structure to store different type of objects.E.g. String, Boolean and other classes.
Is using a Map<String, Object> where using the key you get the according object which assumes that you know how to cast it a good practice?
Is there a better solution?
I need a data structure to store different type of objects.E.g. String , Boolean
Share
That’s a perfect use case for a
PropretyHolderI wrote a while ago. You can read in length about it on my blog. I developed it with immutability in mind, feel free to adapt it to your needs.In general I’d say if you want to profit from type safety in Java you need to know your keys. What I mean by that – it will be hardly possible to develop type safe solution where keys come from external source.
Here’s a special key that knows type of its value (it’s not complete please download the source for complete version):
Then you develop a data structure that utilizes it:
I omit here a lot of unnecessary details please let me know if something is not clear.