Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

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

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 HashMap with a character as a key and an integer as a value. What's the difference between these?

HashMap<Character, Integer> alphabet1 = new HashMap();
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap<Character, Integer>();
Map alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap();
Map alphabet1 = new HashMap();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>();

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<Character, Integer> alphabet1 = new HashMap<>();
HashMap<Character, Integer> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...