Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting java.util.Properties to HashMap<String,String>

Tags:

java

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?

like image 545
Tardis Xu Avatar asked Jun 20 '13 08:06

Tardis Xu


People also ask

Can we convert string to HashMap in Java?

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.


2 Answers

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)); 
like image 67
fge Avatar answered Oct 17 '22 03:10

fge


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.

like image 23
padilo Avatar answered Oct 17 '22 02:10

padilo