Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>(properties);// why wrong?java.util.Properties是java.util.Map的实现,java.util.HashMap's constructor接收Map类型参数。那么,为什么一定要显式转换呢?
发布于 2013-06-20 16:58:31
问题是Properties实现了Map<Object, Object>,而HashMap构造函数需要一个Map<? extends String, ? extends String>。
This answer解释了这个(相当违反直觉的)决定。简而言之:在Java5之前,Properties实现了Map (因为当时还没有泛型)。这意味着您可以将任何Object放入Properties对象中。This is still in the documenation:
因为
Properties继承自Hashtable,所以put和putAll方法可以应用于Properties对象。强烈反对使用它们,因为它们允许调用者插入键或值不是Strings的条目。应该改用setProperty方法。
为了保持兼容性,设计者别无选择,只能让它继承Java5中的Map<Object, Object>。这是努力完全向后兼容的不幸结果,这使得新代码变得不必要地令人费解。
如果您只在Properties对象中使用字符串属性,那么您应该能够在构造函数中使用未经检查的强制转换:
Map<String, String> map = new HashMap<String, String>( (Map<String, String>) properties);或不带任何副本:
Map<String, String> map = (Map<String, String>) properties;https://stackoverflow.com/questions/17209260
复制相似问题