Properties properties = new Properties(); Map<String, String> map = new HashMap<String, String>(properties);// why wrong? java.util.Properties is a implementation of java.util.Map, And java.util.HashMap's constructor receives a Map type param. So, why must it be converted explicitly?
In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output. Input as an array of strings is converted to HashMap.
This is because Properties extends Hashtable<Object, Object> (which, in turn, implements Map<Object, Object>). You attempt to feed that into a Map<String, String>. It is therefore incompatible.
You need to feed string properties one by one into your map...
For instance:
for (final String name: properties.stringPropertyNames()) map.put(name, properties.getProperty(name));
The efficient way to do that is just to cast to a generic Map as follows:
Properties props = new Properties(); Map<String, String> map = (Map)props; This will convert a Map<Object, Object> to a raw Map, which is "ok" for the compiler (only warning). Once we have a raw Map it will cast to Map<String, String> which it also will be "ok" (another warning). You can ignore them with annotation @SuppressWarnings({ "unchecked", "rawtypes" })
This will work because in the JVM the object doesn't really have a generic type. Generic types are just a trick that verifies things at compile time.
If some key or value is not a String it will produce a ClassCastException error. With current Properties implementation this is very unlikely to happen, as long as you don't use the mutable call methods from the super Hashtable<Object,Object> of Properties.
So, if don't do nasty things with your Properties instance this is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With