Java - 投射地图 [英] Java - Cast a Map
问题描述
如何将地图< Object,Object>
投射到地图< String,String>
中最干净方式?
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?
谢谢
推荐答案
我认为解释为什么简单的解决方案不起作用以及为什么你永远不应该使用它是个好主意。
I think it's a good idea to explain why the simple solution doesn't work and why you never, ever should use this.
假设你可以将 List< Object>
投射到 List< String>
(这同样适用于Map,只是一个更简单的界面)。您希望从以下代码中发生什么:
Assume you could cast List<Object>
to List<String>
(the same applies to Map, just a simpler interface). What would you expect to happen from the following code:
List<Object> m = Something;
m.add("Looks good.");
m.add(42);
List<String> s = (List<String>)m; // uhuh, no we don't want that.
String myString = s.get(1); // huh exception here.
现在你可以使用波希米亚人/克里斯解决方案破解它,但你基本上破坏了Java的类型系统。 请勿这样做。您不希望列表< String>
包含整数!稍后进行有趣的调试 - 循环遍历所有变量的附加代码将避免许多令人头疼的问题并且几乎不会出现性能问题。
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.
如果有理由声明Map作为一个Object而不是一个String,有人可能会向它添加任何对象 - 通常你应该能够通过更好的泛型来避免这种情况。
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.
这篇关于Java - 投射地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!