It really depends on what type of security you need. Not a general way to do this is best done as:
Map x = new HashMap();
Note that x is entered as a Map . this makes it much easier to change implementations (in TreeMap or LinkedHashMap ) in the future.
You can use generics to provide a certain level of type safety:
Map<String, Object> x = new HashMap<String, Object>();
In Java 7 and later, you can do
Map<String, Object> x = new HashMap<>();
The above, although more verbose, avoids compiler warnings. In this case, the contents of the HashMap can be any Object , so there can be Integer , int[] , etc. What are you doing.
If you are still using Java 6, Guava Libraries (although this is fairly easy to do yourself) has a newHashMap() method, which avoids duplication of general type information when new executed. It infers the type from the variable declaration (this is a Java function not available to designers before Java 7).
By the way, when you add an int or other primitive, Java does this automatically. This means the code is equivalent to:
x.put("one", Integer.valueOf(1));
You can put the HashMap as a value in another HashMap , but I think there are problems if you do it recursively (this puts the HashMap as a value in itself).
Yishai Aug 28 '09 at 16:12 2009-08-28 16:12
source share