How can I cast a Map<Object,Object> to Map<String,String> in the cleanest way?
Is there a way to do that without iterating over the map?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think it’s a good idea to explain why the simple solution doesn’t work and why you never, ever should use this.
Assume you could cast
List<Object>toList<String>(the same applies to Map, just a simpler interface). What would you expect to happen from the following code:Now you CAN hack it indeed using Bohemians/Chris solution, but you basically destroy Java’s type system. DON’T DO THAT. You don’t want a
List<String>to contain an Integer! Have fun debugging that later on – the additional code of looping through all variables will avoid lots of headaches and hardly is a performance problem.If there’s a reason to declare the Map as taking an Object instead of a String someone may add any object to it – usually you should be able to avoid this with a better generic.