0

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?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158

2 Answers2

8

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.

Cephalopod
  • 14,632
  • 7
  • 51
  • 70
-4

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>();
  • 4
    Why is this better than `new HashMap<>()`? What protection does it offer? – Jeroen Vannevel May 28 '14 at 13:46
  • 4
    Slightly misleading; the second and third alternatives are *exactly* equal. The "extra specificity" that you talk about is actually extra *verbosity* – awksp May 28 '14 at 13:46