If I write
HashMap<String, String> map = new HashMap();
as opposed to
HashMap<String, String> map = new HashMap<>();
or as opposed to
HashMap<String, String> map = new HashMap<String, String>();
will the 1st one be unsafe in any way?
If I write
HashMap<String, String> map = new HashMap();
as opposed to
HashMap<String, String> map = new HashMap<>();
or as opposed to
HashMap<String, String> map = new HashMap<String, String>();
will the 1st one be unsafe in any way?
The second is just an abbreviation of the third alternative.
The first way can cause problems if you use a different constructor, because it ignores generics.
For instance, the following compiles:
Map<Integer, Integer> intMap = ...;
Map<String, String> strMap = new HashMap(intMap);
It will even execute without errors because there are no generic checks at runtime. But if intMap
contained data and you access it from strMap
(eg., by iterating over keys), you will get a runtime exception.
Such a bug would be very hard to track because the exception might occur far away from the offending line.
So, in your particular case it wouldn't cause problems, but if you make this a habit you will run into problems eventually. Furthermore, you will get compiler warnings which you would have to suppress or ignore, both things that should be avoided.
Alex,
It is not likely "unsafe", but the extra specificity of the third example provides the greatest degree of typesafe protection from the runtime.
I would recommend using the interface with generics to instantiate:
Map<String,String> map = new HashMap<String,String>();