It really depends on what kind of type safety you need. The non-generic way of doing it is best done as:
Map x = new HashMap();
Note that x
is typed as a Map
. this makes it much easier to change implementations (to a TreeMap
or a LinkedHashMap
) in the future.
You can use generics to ensure 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, while more verbose, avoids compiler warnings. In this case the content of the HashMap
can be any Object
, so that can be Integer
, int[]
, etc. which is what you are doing.
If you are still using Java 6, Guava Libraries (although it is easy enough to do yourself) has a method called newHashMap()
which avoids the need to duplicate the generic typing information when you do a new
. It infers the type from the variable declaration (this is a Java feature not available on constructors prior to Java 7).
By the way, when you add an int or other primitive, Java is autoboxing it. That means that the code is equivalent to:
x.put("one", Integer.valueOf(1));
You can certainly put a HashMap
as a value in another HashMap
, but I think there are issues if you do it recursively (that is put the HashMap
as a value in itself).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…