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

前端 未结 3 1959
夕颜
夕颜 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:15

    Anything involving HashMap or Map without a type argument (the angle brackets < and > and the part between them) is a raw type and shouldn't be used. A raw type is not generic and lets you do unsafe things.

    The "correct" ways are

    Map alphabet1 = new HashMap();
    HashMap alphabet1 = new HashMap();
    

    The first uses the interface Map as the reference type. It is generally more idiomatic and a good style.

    Also another way you did not mention, using the Java 7 diamond operator

    Map alphabet1 = new HashMap<>();
    HashMap alphabet1 = new HashMap<>();
    

    Which is more or less equivalent to the first two correct ways. The arguments to the reference type on the left-hand side are supplied implicitly to the constructor on the right-hand side.

提交回复
热议问题