What's the difference between these ways of initializing a HashMap?

前端 未结 3 1934
夕颜
夕颜 2020-12-10 21:38

I used a HashMap for my program and it works fine, but I don\'t understand the difference between these initializations of HashMap.

Let\'s say I\'m implementing a Ha

3条回答
  •  囚心锁ツ
    2020-12-10 22:24

    You missed the right choice:

    Map alphabet1 = new HashMap();
    
    1. Generics declaration allows compiler to check your 'alphabet1' usages during compile-time.
    2. Map/HashMap on left side declares how your 'alphabet1' variable should be considered: either as Map (interface) or HashMap (instance of concrete class). Of course interface is preferred - it makes your code more robust to further changes.

提交回复
热议问题